☕ Java Intermediate

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.