Accessing ArrayList Elements

To access a single ArrayList element, use ArrayList.get() method. To print all elements, you can use a simple for loop with ArrayList.get() method or use an Iterator object to iterate through the ArrayList.

import java.util.*;

public class ArrayListPrint {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>();
    al.add(new Integer(11));
    al.add(new Integer(13));
    al.add(new Integer(17));

    // prints third element
    System.out.println(al.get(2));

    // prints all elements
    for (int i = 0; i < al.size(); i++) {
       System.out.println(al.get(i));
    }

    // uses Iterator to print all elements
    Iterator<Integer> itr = al.iterator();
    while (itr.hasNext()) {
       System.out.println(itr.next());
    }
  }
}
Technologies: