Introduction
This article describes how the ArrayList class in Java Collections work.
What is the ArrayList class in Java?
Java arrays are of a fixed length. When arrays are created, they are unable to grow or shrink, in other words, we must know in advance how many elements we need so that the array will hold them. Now, the ArrayList class extends Array-List and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
This class supports mainly three constructors.
- ArrayList(int capacity)
- Apart from the methods inherited from its parent classes, ArrayList defines the following methods.
- ArrayList( )
- This constructor builds an array list that is initialized with the elements of the collection cln.
- ArrayList(Collection cln)
- This constructor builds an array list that has the specified initial capacity. The capacity grows automatically as elements are added to an array list.
Example: The following example contains various methods used by the ArrayList class.
- import java.util.*;
- public class ArrayListEx1 {
- public static void main(String args[]) {
- ArrayList arylst = new ArrayList();
- System.out.println("size of initialized arraylist: " + arylst.size());
- arylst.add("C");
- arylst.add("P");
- arylst.add("Q");
- arylst.add("R");
- arylst.add("S");
- arylst.add("T");
- arylst.add(1, "P2");
- System.out.println("Size of arraylist after additions: " + arylst.size());
- System.out.println("Contents of arraylist: " + arylst);
- arylst.remove("T");
- arylst.remove(2);
- System.out.println("After deletion size of arraylist: " + arylst.size());
- System.out.println("The contents of arraylist: " + arylst);
- }
- }
Output
The following are two ways to iterate the elements of the collection:
- By Iterator interface.
- By For-each loop
1. By using a For-each loop
Example
- import java.util.*;
- class ArrayListEx2 {
- public static void main(String args[]) {
- ArrayList arylst = new ArrayList();
- arylst.add("John");
- arylst.add("Paul");
- arylst.add("Jaun");
- arylst.add("San");
- for (Object obj: arylst)
- System.out.println(obj);
- }
- }




Join the conversation! Your thoughts help the community grow.