Difference between Iterator and ListIterator in Java?
In this tutorial we will see about difference between java.util.Iterator and java.util.ListIterator interfaces. Both interface are used to traverse values from the collection Object. But the differences are
- Iterator can traverse only in forward direction, where as ListIterator can traverse in both (bidirectional).
- Iterator can be used to traverse values in List and Set collections, where as ListIterator is used to traverse only in List.
- ListIterator derived from Iterator interface and contains functions like remove(), previous(), next(), nextIndex(), previousIndex() etc.,
Lets see examples for both Iterator and ListIterator as how its used on Collection Object.
Iterator Example:
public class IteratorTest {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add("java");
myList.add("collections");
myList.add("API");
myList.add("important");
myList.add("interview");
myList.add("questions");
System.out.println("LIST BEFORE REMOVE : "+myList);
Iterator<String> itr = myList.iterator();
while(itr.hasNext()){
String val = itr.next();
if(val.equals("API")){
// Removing "API" value from ArrayList
itr.remove();
}
}
System.out.println("LIST AFTER REMOVE : "+myList);
}
}
OUTPUT:
LIST BEFORE REMOVE : [java, collections, API, important, interview, questions]
LIST AFTER REMOVE : [java, collections, important, interview, questions]
ListIterator Example:
public class ListIteratorTest {
public static void main(String[] args) {
List<String> myList = new ArrayList<String>();
myList.add("java");
myList.add("collections");
myList.add("API");
myList.add("important");
myList.add("interview");
myList.add("questions");
System.out.println("LIST : "+myList);
ListIterator<String> itr = myList.listIterator();
while(itr.hasNext()){
String val=itr.next();
if(val.equals("API")){
// moving to previous element
itr.previous();
System.out.println("PREVIOUS VALUE : "+myList.get(itr.previousIndex()));
// moving to forward element
itr.next();
System.out.println("NEXT VALUE : "+myList.get(itr.nextIndex()));
}
}
}
}
OUTPUT:
LIST : [java, collections, API, important, interview, questions]
PREVIOUS VALUE : collections
NEXT VALUE : important