What is an Iterator in Java?
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.
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?