Question
Does Java create a new instance of iterator() each time it's called?
Answer
In Java, the behavior of the iterator() method varies depending on the collection type used. Understanding when a new instance of an iterator is created can help optimize the handling of collections and ensure correct iteration over elements.
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
Iterator<String> it1 = list.iterator(); // New instance created
Iterator<String> it2 = list.iterator(); // Another new instance created
while (it1.hasNext()) {
System.out.println(it1.next()); // Output: A, B
}
while (it2.hasNext()) {
System.out.println(it2.next()); // Output: A, B (separate iteration)
}
Causes
- The iterator() method is designed to return a new iterator instance for certain collection types such as ArrayList and HashSet.
- Other collections, like LinkedList, may also create a new iterator each time the method is invoked.
Solutions
- To avoid unnecessary overhead, you can store the length of the collection in a variable if you are iterating multiple times.
- For collections that do not change size, consider reusing the same iterator instance when possible.
Common Mistakes
Mistake: Assuming that an iterator is a singleton for the collection.
Solution: Remember that calling iterator() produces a new instance; iterate through one instance at a time.
Mistake: Neglecting to check if the collection was modified during iteration.
Solution: Always ensure the collection is not changed while an iterator is being used to avoid ConcurrentModificationException.
Helpers
- Java iterator method
- Java collections iterator
- Java create new iterator instance
- Java iterator explanation