Difference between an Iterator and ListIterator in Java
Iterators are used in Collection framework in Java to retrieve elements one by one. It can be applied to any Collection object. By using Iterator, we can perform both read and remove operations. Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface. Iterator is the only cursor available for entire collection framework. Iterator object can be created by calling iterator() method present in Collection interface.
// Here "c" is any Collection object. itr is of // type Iterator interface and refers to "c" Iterator itr = c.iterator();
ListIterator It is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-directional iteration. ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator. ListIterator object can be created by calling listIterator() method present in List interface.
// Here "l" is any List object, ltr is of type // ListIterator interface and refers to "l" ListIterator ltr = l.listIterator();
Differences between Iterator and ListIterator:
- Iterator can traverse only in forward direction whereas ListIterator traverses both in forward and backward directions. Example:
Iterator: Forward traversal: 1 2 3 4 5 ListIterator: Forward Traversal : 1 2 3 4 5 Backward Traversal : 5 4 3 2 1
- ListIterator can help to replace an element whereas Iterator cannot. Example:
Elements of ArrayList: 1 2 3 4 5 Now the ArrayList elements are: 80000 2 3 4 5
- OUTPUT Table showing Difference between Iterator and ListIterator
|Can traverse elements present in Collection only in the forward direction.||Can traverse elements present in Collection both in forward and backward directions.|
|Helps to traverse Map, List and Set.||Can only traverse List and not the other two.|
|Indexes cannot be obtained by using Iterator.||It has methods like nextIndex() and previousIndex() to obtain indexes of elements at any time while traversing List.|
|Cannot modify or replace elements present in Collection||We can modify or replace elements with the help of set(E e)|
|Cannot add elements and it throws ConcurrentModificationException.||Can easily add elements to a collection at any time.|
|Certain methods of Iterator are next(), remove() and hasNext().||Certain methods of ListIterator are next(), previous(), hasNext(), hasPrevious(), add(E e).|
Please Login to comment...