Sobes.tech
Junior

What is an iterator and what is it used for?

sobes.tech AI

Answer from AI

An iterator in Java is an object that allows sequential traversal of the elements in a collection without needing to know its internal structure.

Main purposes of using an iterator:

  • Abstraction: Provides a unified way to traverse elements for different types of collections (lists, sets, etc.).
  • Safety: Allows removing elements from the collection during iteration without breaking the iteration logic.
  • Independence: Traversal of elements is independent of the specific implementation of the collection.

The Iterator<E> interface defines three main methods:

  • hasNext(): Returns true if there are more elements in the iteration.
  • next(): Returns the next element in the iteration.
  • remove(): Removes from the underlying collection the last element returned by the iterator.

Example of usage:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

// Example of using an iterator
public class IteratorExample {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        Iterator<String> iterator = list.iterator();

        // Traversing elements using the iterator
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.println(element);

            // Removing an element during iteration (example)
            if (element.equals("Banana")) {
                iterator.remove();
            }
        }

        System.out.println("List after removal: " + list);
    }
}
What is an iterator and what is it used for? — Java - sobes.tech