Iterators

When working with collections in Java, it’s often necessary to traverse through elements to perform some operations. One of the most common ways to do this is by using Iterators. An Iterator is an object in Java that allows you to loop through elements of a collection, such as a List, Set, or Queue. It provides a simple, unified way to iterate over various data structures without exposing the underlying implementation.

An Iterator is an interface in Java that provides methods to traverse through a collection. It allows access to the elements of a collection in a sequential manner. With an Iterator, you can perform the following actions:

  • Access elements in a collection
  • Check if there are more elements left to access
  • Remove elements during iteration

Example

  • hasNext(): Before accessing the next element, we check if there are more elements in the collection using iterator.hasNext().
  • next(): We use iterator.next() to retrieve the current element in the iteration.
  • remove(): When the current number is 30, we use iterator.remove() to remove it from the list.

Why Use Iterators?

  • Uniformity: Iterators provide a consistent way of iterating over different types of collections, whether you’re working with a List, Set, or Queue.
  • Safety: Using the remove() method via the iterator is safer than using the remove() method of the collection itself during iteration, as it avoids ConcurrentModificationException.
  • Flexibility: Iterators can be used with both static and dynamic collections, and they abstract away the underlying details of how elements are stored.