ArrayList and iterator: Example 1

Code Explanation

LineDescription
6Creates an ArrayList named customerList of type String
7 – 8Creates 2 variables of type String and assigns them the values Smith and Johnson.
9 – 10Adds the previously created variables to the ArrayList.
11Create iterator variable of customerList named iter
12Uses the iterator variable to loop over the ArrayList
13Outputs every single element of the ArrayList
import java.util.ArrayList;
import java.util.Iterator;

class ArrayListAndIterator {
	public static void main(String[] args) {
		ArrayList<String> customerList = new ArrayList<String>();
		String k1 = "Smith";
		String k2 = "Johnson";
		customerList.add(k1);
		customerList.add(k2);
		Iterator<String> iter = customerList.iterator();
		while (iter.hasNext()) {
			System.out.println(iter.next());
		}
	}
}
Output
Smith
Johnson