Sobes.tech
Senior

How does the Iterator interface work? What methods does it contain?

sobes.tech AI

Answer from AI

The Iterator interface in Java is used for sequential traversal of collections without exposing their internal structure. The main methods of the interface:

  • boolean hasNext() — returns true if there is a next element in the collection.
  • E next() — returns the next element in the collection.
  • default void remove() — removes the last returned element (optional).

Example of usage:

Iterator<String> iterator = list.iterator();
while(iterator.hasNext()) {
    String item = iterator.next();
    System.out.println(item);
}