ArrayList with Example

ArrayList is resizable-array implementation of the List interface. ArrayList is a non-synchronized dynamically growable array with efficient access by index.   Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. This class is equivalent to Vector, except that it is unsynchronized.

ArrayList Example:


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListExample {

 public static void main(String[] args) {

  List list = new ArrayList();

  System.out.println("Initial size of ArrayList: " 
    + list.size() + "\n");

  list.add(new Integer(1));
  list.add(2);
  list.add(new Integer(3));
  list.add(new Integer(5));
  list.add(new Integer(3));
  list.add(new Integer(2));

  System.out.println("Size of ArrayList after " +
    "adding the objects: "  + list.size() + "\n");
  System.out.println("ArrayList Values : " + 
    list + "\n");

  Iterator it = list.iterator();
  System.out.print("List Values Using Iterator : ");
  while (it.hasNext()) {
   System.out.print(it.next() + " ");
  }

  System.out.println("\n ");

  System.out.print("ArrayList Values using" +
    " advance for loop");
  for (Integer integer : list) {
   System.out.print(integer + " ");
  }
  System.out.println("\n ");

  // Convert List To Array
  Integer[] intArray = list.toArray(new Integer[list.size()]);
  System.out.print("Array Values: ");
  for (Integer o : intArray) {
   System.out.print( o + " ");
  }

 }

}
Output:
Initial size of ArrayList: 0

Size of ArrayList after adding the objects: 6

ArrayList Values : [1, 2, 3, 5, 3, 2]

ArrayList Values Using Iterator : 1 2 3 5 3 2 
 
ArrayList Values using advance for loop1 2 3 5 3 2 
 
Array Values: 1 2 3 5 3 2 

Search: