WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Advanced · question 49 of 100

What is the difference between an Iterator and a ListIterator in Java Collections, and when would you use one over the other?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java Collections, Iterator and ListIterator are two interfaces that allow you to iterate over a collection of elements. While they both have similar functionality, there are some differences that make them useful in different scenarios.

Iterator:

Iterator is a basic interface in the Java Collections Framework that can be used to traverse any collection that implements the Iterable interface. It is used for iterating over a collection of elements in a forward direction only. It can remove elements from the collection during iteration. It has three methods: hasNext(), next(), and remove().

Example Code:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Mango");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
  String element = iterator.next();
  System.out.println(element);
  if (element.equals("Banana")) {
    iterator.remove();
  }
}

ListIterator:

ListIterator is an extended interface of Iterator that can be used to traverse only those collections that implement the List interface. It is used for iterating over a list of elements in both forward and backward directions. It can add, remove, and replace elements in the list during iteration. It has eight methods: hasNext(), next(), hasPrevious(), previous(), nextIndex(), previousIndex(), remove(), and set().

Example Code:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Mango");

ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
  String element = listIterator.next();
  System.out.println(element);
  if (element.equals("Banana")) {
    listIterator.add("Orange");
    listIterator.remove();
  }
}

When to use Iterator or ListIterator:

If you want to iterate over a collection in a forward direction and you don’t need to modify the collection while iterating, use an Iterator. If you want to iterate over a list in both forward and backward directions and you need to modify the list while iterating, use a ListIterator.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics