The following example code demonstrates how to Display Elements of an ArrayList Using an Iterator in Java.
Here is a Java program that implements the given requirement.
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("dates");
list.add("elderberry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
This program creates an ArrayList of strings list
, adds 5 elements to it, and then creates an iterator iterator
using the iterator()
method of the ArrayList. The elements of the list are displayed using a while
loop, in which the iterator.hasNext()
method returns true until there are no more elements in the list, and the iterator.next()
method returns the next element in the list.