Loading

Q1. What is an Iterator in Java, and why is it used?

 An Iterator is an interface in Java used to traverse collections one element at a time. It provides a uniform way to access elements regardless of the collection type.






Q2. What are the key methods of the Iterator interface?
  • hasNext() returns true if more elements exist.
  • next() returns the next element.
  • remove() removes the last element returned by next().






Q3. How does Iterator differ from Enumeration?
  • Enumeration is legacy and only allows element traversal.
  • Iterator is modern, allows element removal, and is safer with fail-fast behavior.






Q4. Is Iterator fail-fast or fail-safe?

Iterators of most Java collections (like ArrayList, HashMap) are fail-fast, meaning they throw ConcurrentModificationException if the collection is modified while iterating. Some classes (like CopyOnWriteArrayList) provide fail-safe iterators.







Q5. What is the difference between Iterator and ListIterator?
  • Iterator works with all collections, forward-only traversal.
  • ListIterator works only with List, allows bidirectional traversal, and provides more methods like previous(), set(), and add().