The following article describes the Difference Between Iterator and ListIterator in Java.
In Java, Iterator
and ListIterator
are both interfaces used to traverse a collection of elements. They are both part of the java.util package and provide similar functionality, but with some key differences.
The main difference between Iterator
and ListIterator
is the direction of iteration. Iterator
is used to iterate over a collection of elements in a forward direction only. On the other hand, ListIterator
provides bidirectional iteration, meaning that you can iterate through the elements in both the forward and backward directions.
Another difference is that ListIterator
provides access to the current index of the iteration, while Iterator
does not. This means that with ListIterator
, you can add or remove elements from the list while iterating through it, as well as retrieve the previous and next elements in the iteration.
Here is an example of how to use Iterator
in Java:
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
int value = iter.next();
System.out.println(value);
}
}
}
And here is an example of how to use ListIterator
in Java:
javaCopy codeimport java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
ListIterator<Integer> iter = list.listIterator();
while (iter.hasNext()) {
int value = iter.next();
System.out.println(value);
}
}
}
In conclusion, if you need to traverse a collection in a forward direction only, use Iterator
. If you need bidirectional iteration, as well as access to the current index of the iteration, use ListIterator
.