Interview Questions
Java
java collections interview questions
Java Interview Questions
Java interview questions
Difference between an Iterator and ListIterator in Java
Iterator
and ListIterator
are interfaces in Java that allow us to iterate over a collection of objects. However, there are some differences between them:
- The
Iterator
interface can be used to iterate over any collection, whereas theListIterator
interface can be used to iterate only over lists. - The
ListIterator
interface extends theIterator
interface and provides additional methods to traverse the list in both forward and backward directions. - With a
ListIterator
, you can add and remove elements from the list while iterating, but with anIterator
, you can only remove elements.
Here’s an example code that demonstrates the difference between the two:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class IteratorVsListIteratorExample {
public static void main(String[] args) {
List<String> myList = new ArrayList<>();
myList.add("apple");
myList.add("banana");
myList.add("cherry");
// Using Iterator to iterate over the list
Iterator<String> it = myList.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
// Using ListIterator to iterate over the list in backward direction
ListIterator<String> lit = myList.listIterator(myList.size());
while (lit.hasPrevious()) {
System.out.println(lit.previous());
}
}
}
In the above code, we have used an Iterator
to iterate over the list in forward direction, and a ListIterator
to iterate over the list in backward direction. Note that the ListIterator
is created by passing the size of the list as the starting index, which allows us to iterate over the list in reverse order.