ArrayList and Iterator: Example 1

This Java code defines a class named ArrayListAndIterator that contains a main method.

The main method creates an ArrayList of type String named customerList. It then declares two strings k1 and k2 and adds them to the customerList using the add method.

Next, the code creates an Iterator named iter that is obtained from the iterator method of the customerList object. The Iterator is an interface that is used to traverse elements in a collection and is commonly used to traverse ArrayLists.

Finally, the code uses a while loop to iterate through the customerList using the Iterator. The while loop continues as long as the iter.hasNext() method returns true, indicating that there are more elements in the customerList to be processed. Inside the while loop, the code calls the iter.next() method to retrieve the next element in the customerList and prints it to the console using System.out.println. The loop continues until all elements have been processed and iter.hasNext() returns false.

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