Curriculum
In Java, an iterator is an interface that allows us to access elements of a collection in a sequential manner. It provides a way to iterate over a collection without exposing the underlying implementation of the collection. Here is an example of how an iterator is used in Java:
import java.util.ArrayList; import java.util.Iterator; public class IteratorExample { public static void main(String[] args) { ArrayList<String> colors = new ArrayList<>(); colors.add("Red"); colors.add("Green"); colors.add("Blue"); Iterator<String> iterator = colors.iterator(); while (iterator.hasNext()) { String color = iterator.next(); System.out.println(color); } } }
In this example, we have an ArrayList of colors and we create an iterator using the iterator()
method of the ArrayList class. We then use the hasNext()
method of the iterator to check if there are more elements in the collection, and the next()
method to retrieve the next element. The loop continues until there are no more elements in the collection.
The Iterator interface in Java has the following methods:
boolean hasNext()
: Returns true if there are more elements in the collection.E next()
: Returns the next element in the collection.void remove()
: Removes the last element returned by the iterator from the collection.Note that the remove()
method is optional and may not be supported by all collections.