What is an Iterator in Java?
Why Interviewers Ask This
This tests whether you can apply Java knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
Answer
An Iterator is an object that enables traversing a collection one element at a time without exposing the underlying data structure. The Iterator interface has three methods: hasNext() (returns true if more elements exist), next() (returns the next element), and remove() (removes the last element returned by next() — the safe way to remove during iteration). To get an iterator: Iterator<String> it = list.iterator();. Iterating with an iterator while modifying the collection through the collection itself throws ConcurrentModificationException. Use it.remove() instead of list.remove() for safe removal during iteration.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Java experience.
Previous
What is the difference between HashSet and TreeSet?
Next
What is the difference between fail-fast and fail-safe iterators?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?