This example shows how to use an iterator with ArrayList. Iterator can be used with other collections.
import java.util.*;
public class ArrayListIterator {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Integer(11));
al.add(new Integer(13));
al.add(new Integer(17));
Iterator itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
output
11
13
17
Note that if you are using Java 5 or above, you will get the following warning.
Type ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
This is because Java 5 introduced the concept of generics where you are encouraged to define types for interfaces. To remove these warnings, add type parameters as in the following example.
import java.util.*;
public class ArrayListIterator {
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));
Iterator<strong><Integer></strong> itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
output
11
13
17
In this example, we created an ArrayList that stores Integer objects. Three Integers are added. An Iterator is instantiated for the ArrayList. We loop through the entire ArrayList and print each element. itr.next() returns a String which is printed by System.out.print.