The ArrayList Class in java

The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this declaration:

class ArrayList<E>

Here, specifies the type of objects that the list will hold.

ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large an array you need. To handle this situation, the Collections Framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk.

ArrayList has the constructors

ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)

The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

Demonstrate ArrayList

import java.util.*;

class ArrayListDemo {

public static void main(String args[]) { // Create an array list.

ArrayList<String> al = new ArrayList<String>();

System.out.println("Initial size of al: " + al.size());

//Add elements to the array list. al.add("C");





al.add("F"); al.add(1, "A2");

System.out.println("Size of al after additions: " + al.size());

//Display the array list. System.out.println("Contents of al: " + al);

//Remove elements from the array list. al.remove("F");


System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);



The output from this program is shown here:

Initial size of al: 0

Size of al after additions: 7

Contents of al: [C, A2, A, E, B, D, F]

Size of al after deletions: 5

Contents of al: [C, A2, E, B, D]

Leave a Comment