What is an Iterator in Java?

An Iterator is an object that enables traversal through a collection, one element at a time. It provides methods to access and remove elements during iteration.

Difference Between Iterator and ListIterator

While Iterator allows unidirectional traversal, ListIterator supports bidirectional traversal and additional functionalities like adding elements and obtaining indexes.

Advantages of Using Iterator

  • Simplified Traversal: Makes iterating over collections easy.
  • Supports Removal: Allows safe removal of elements during iteration.

Disadvantages of Iterator

  • Limited Functionality: Cannot add or replace elements.
  • Single-Direction Traversal: Only moves forward through the collection.

How to Use an Iterator with ArrayList

To use an Iterator, first create one from the ArrayList:

Iterator<String> iterator = names.iterator();

Traversing Elements with Iterator

Using the Iterator to traverse elements:

while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Basic Iterator Methods

  • hasNext(): Returns true if there are more elements.
  • next(): Returns the next element.
  • remove(): Removes the last element returned by next().

Example of Using an Iterator

Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    System.out.println(name);
}

Differences Between Iterator and ListIterator

ListIterator offers additional features like:

  • Bidirectional Iteration: Allows moving both forward and backward.
  • Index Manipulation: Can retrieve the index of elements.

When to Use Iterator vs. ListIterator

  • Use Iterator: When you only need to traverse forward.
  • Use ListIterator: When you need to traverse in both directions or manipulate the list during iteration.