Can you explain how Iterator works within the Java Collection Framework?

An Iterator is an interface in the Java Collection Framework that provides a standard way to traverse elements in a collection one at a time. It allows sequential access to collection elements without exposing the internal structure of the collection.

Key Points: • Iterator works with most Collection Framework classes such as List, Set, and Queue. • It provides methods like hasNext(), next(), and remove(). • It enables safe traversal of collection elements. • It eliminates the need to know how a collection is internally implemented. • It supports element removal during iteration without causing errors.

How Iterator Works:

The Iterator interface mainly provides three methods:

1. hasNext()

Checks whether more elements are available.

2. next()

Returns the next element in the collection.

3. remove()

Removes the current element from the collection safely.

Example: Suppose we have a list of technologies and want to access each element one by one.

Code Example:

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

public class Demo {

    public static void main(String[] args) {

        List<String> technologies =
                new ArrayList<>();

        technologies.add("Java");
        technologies.add("Spring");
        technologies.add("Hibernate");

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

        while (iterator.hasNext()) {

            System.out.println(iterator.next());
        }
    }
}

Output:

Java
Spring
Hibernate

Removing Elements Using Iterator:

Using Iterator's remove() method is safer than removing elements directly from the collection while iterating.

Code Example:

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

public class Demo {

    public static void main(String[] args) {

        List<String> names =
                new ArrayList<>();

        names.add("John");
        names.add("David");
        names.add("Mike");

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

        while (iterator.hasNext()) {

            String name = iterator.next();

            if (name.equals("David")) {

                iterator.remove();
            }
        }

        System.out.println(names);
    }
}

Output:

[John, Mike]

Why Not Use Collection.remove() During Iteration?

Using collection.remove() while iterating may cause a ConcurrentModificationException.

Iterator's remove() method avoids this problem by updating the collection safely during traversal.

Advantages of Iterator:

• Uniform way to traverse collections • Works with different collection types • Supports safe element removal • Hides collection implementation details • Improves code flexibility

Iterator vs Enhanced For Loop:

Iterator: • Supports remove() • More control during traversal

Enhanced For Loop: • Simpler syntax • Does not support safe element removal

Common Iterator Methods:

• hasNext() → Checks if more elements exist • next() → Retrieves the next element • remove() → Removes the current element

Interview Tip: A concise interview answer is:

"Iterator is an interface used to traverse elements of a collection sequentially. It provides methods such as hasNext(), next(), and remove(), allowing safe iteration and element removal without exposing the collection's internal implementation."