ArrayList and iterator: Example 2

Code Explanation

LineDescription
6Creates an ArrayList named list of type Integer
8 – 10Adds the numbers 2, 4 and 6 to list
13Create iterator variable of list named iter
14Uses the iterator variable to loop over the ArrayList
15Outputs every single element of the ArrayList
import java.util.ArrayList;
import java.util.Iterator;

class ArrayListIteratorExample {
	public static void main(String[] args) {
		ArrayList<Integer> list = new ArrayList<Integer>();
	
		list.add(2);
		list.add(4);
		list.add(6);

		// output elements using iterator
		Iterator<Integer> iter = list.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}
}
Output
2
4
6