This Java code defines a class named ArrayListIteratorExample
that contains a main
method.
The main
method creates an ArrayList
of type Integer
named list
. It then uses the add
method to add three integers (2, 4, and 6) to the list.
Next, the code creates an Iterator
named iter
for the list
by calling the iterator
method on the list
object. The Iterator
is an interface that is used to traverse elements in a collection and is commonly used to traverse ArrayList
s.
Finally, the code uses a while
loop to iterate through the list
using the Iterator
. The while
loop continues as long as the iter.hasNext()
method returns true
, indicating that there are more elements in the list
to be processed. Inside the while
loop, the code calls the iter.next()
method to retrieve the next element in the list
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 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());
}
}
}
2
4
6