Basics of the ArrayList class

The java.util.ArrayList class is a convenient class for storing lists of objects. The following example shows how to do some simple, common tasks with an ArrayList.

// Make an array list containing strings.
ArrayList<String> A = new ArrayList<String>();
// Add some elements to the list.
A.add("Hello.");
A.add("This is a test.");
// Iterate over the elements of the list
for(int n = 0;n < A.size();n++)
  System.out.println(A.get(n));
// Remove the last item
A.remove(A.size()-1);
// Alternative way to remove the last item.
String last = A.get(A.size()-1);
A.remove(last);

Alternative ways to iterate over an ArrayList

The loop above demonstrates the most common way to iterate over the elements of an ArrayList:

for(int n = 0;n < A.size();n++)
  System.out.println(A.get(n));

An alternative technique takes advantage of the fact that the ArrayList class implements the Collection interface. Given a Collection, we ask it to produce an Iterator. By using the Iterator's hasNext() and next() methods, we can iterate over the list:

Iterator<String> iter = A.iterator();
while(iter.hasNext())
  System.out.println(iter.next());

Yet a third alternative, using the for-each loop:

for(String str : A)
  System.out.println(str);

This is read "for each String str in A, print the string.