Iterator is an interface that is used to iterate the collection elements. It is part of java collection framework. Iterator Interface is used to traverse a list in forward direction, enabling us to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.
ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implements the List Interface.
Following is a list of differences between Iterator and Enumeration.
Iterator | ListIterator |
Iterator we can traverse the list of objects in forward direction. | ListIterator can traverse the collection in both directions that is forward as well as backward. |
Iterator can be used for traversing Set, List and Map. | ListIterator can only be used for traversing a List. |
We cannot obtain indexes while using Iterator. | By using nextIndex() and previousIndex() in ListIterator, we can obtain indexes at any point of time while traversing a list. |
We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException when you try to do it. | We can add element at any point of time while traversing a list using ListIterator. |
We cannot replace the existing element value when using Iterator. | But in ListIterator we can replace the last element returned by next() or previous() methods by using set(E e) method. |
Sample Java code to demonstrate Iterator and ListIterator
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IteratorListIteratorExample { static public void main(String [] args) { List listObject = new ArrayList(); listObject.add("Sachin"); listObject.add("Kapil"); ListIterator listIteratorObject = listObject.listIterator(); System.out.println("ListIterator object output in forward direction:"); System.out.println(""); while( listIteratorObject.hasNext() ) { System.out.println(listIteratorObject.next()); } System.out.println("ListIterator object output in backward direction:"); System.out.println(""); while( listIteratorObject.hasPrevious() ) { System.out.println(listIteratorObject.previous()); } List iteratorListObject = new ArrayList(); iteratorListObject.add("Virat"); iteratorListObject.add("Suresh"); iteratorListObject.add("Chahal"); Iterator javaHungryIterator = iteratorListObject.iterator(); System.out.println("Iterator object output in forward direction:"); while( javaHungryIterator.hasNext() ) { System.out.println(javaHungryIterator.next()); } } }
Hope you have enjoyed reading Difference between Iterator and ListIterator in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp