ArrayList in Java

ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

  • ArrayList inherits AbstractList class and implements List interface.
  • ArrayList is initialized by a size, however the size can increase if collection grows or shrunk if objects are removed from the collection.
  • Java ArrayList allows us to randomly access the list.
  • ArrayList can not be used for primitive types, like int, char, etc. We need a wrapper class for such cases (see this for details).
  • ArrayList in Java can be seen as similar to vector in C++.

java-arraylist

Let us look at the code to create generic ArrayList-

// Creating generic integer ArrayList
ArrayList<Integer> arrli = new ArrayList<Integer>();
// Java program to demonstrate working of ArrayList in Java
import java.io.*;
import java.util.*;

class arrayli
{
    public static void main(String[] args)
                       throws IOException
    {
        // size of ArrayList
        int n = 5;

        //declaring ArrayList with initial size n
        ArrayList<Integer> arrli = new ArrayList<Integer>(n);

        // Appending the new element at the end of the list
        for (int i=1; i<=n; i++)
            arrli.add(i);

        // Printing elements
        System.out.println(arrli);

        // Remove element at index 3
        arrli.remove(3);

        // Displaying ArrayList after deletion
        System.out.println(arrli);

        // Printing elements one by one
        for (int i=0; i<arrli.size(); i++)
            System.out.print(arrli.get(i)+" ");
    }
}

Input:

[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1 2 3 5 

Also see – Array vs ArrayList in Java

This article is contributed by Bharat Sahni. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




Recommended Posts:



1.8 Average Difficulty : 1.8/5.0
Based on 19 vote(s)