JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Difference between Iterator and ListIterator in Java?

The Iterator is the standard way to traverse a collection in Java. You can use Iterator to traverse a List, Set, Map, Stack, Queue or any Collection, but you might not know that there is another way to traverse over List in Java? Yes, it's called the ListIterator. There are many differences between Iterator and ListIterator in Java, but the most significant of them is that Iterator only allows you to traverse in one direction i.e. forward, you have just got a next() method to get the next element, there is no previous() method to get the previous element. On the other hand, ListIterator allows you to traverse the list in both directions i.e. forward and backward. It has got both next() and previous() method to access the next and previous element from List.

Unfortunately, ListIterator only supports the List interface, you cannot use it to traverse over Map or Set in Java.


Iterator vs ListIterator

You can differentiate between Iterator and ListIterator on following topics :
  • Direction of traversal
  • Operation allowed during iteration
  • Supported Collection classes
  • Iterating from any arbitrary element
  • Supported methods

Traversal direction
As I told you in the first paragraph that fundamental difference between Iterator and ListIterator is that former allow traversal only in forward direction i.e. you cannot go back once you move forward, which is what sometimes you need. ListIterator gives you that functionality via previous() method. Similar to next() this method returns the previous element hence support traversal in the backward direction  (see Core Java Volume 1 - Fundamentals by Cay. S. Horstmann)

Here is an example of traversing a List in the reverse direction :

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Java Program to demonstrate difference between Iterator and ListIterator in
 * Java.
 *
 *
 */
public class IteratorAndListIterator{

    public static void main(String[] args) {

        List<String> wishlist = new ArrayList<>();
        wishlist.add("Bose Bluetooth HeadSet");
        wishlist.add("Kindle Fire HD10");
        wishlist.add("Good HDMI Cable");
        wishlist.add("128GB Micro SD Card");
        wishlist.add("Good Blueray Player");

        // Iterating in forward direction
        Iterator<String> itr = wishlist.iterator();
        StringBuilder sb = new StringBuilder();
        while (itr.hasNext()) {
            sb.append(itr.next()).append(",");
        }
        System.out.println("forward order list: " + sb.toString());

        // Iterating in reverse direction
        // getting ListIterator from last Index
        ListIterator<String> listItr = wishlist.listIterator(wishlist.size());
        sb = new StringBuilder();
        while (listItr.hasPrevious()) {
            sb.append(listItr.previous()).append(" ");
        }
        System.out.println("reverse order list: " + sb.toString());
    }

}

Output
forward order list: Bose Bluetooth HeadSet,Kindle Fire HD10,
Good HDMI Cable,128GB Micro SD Card,Good Blueray Player,
reverse order list: Good Blueray Player 128GB Micro SD Card 
Good HDMI Cable Kindle Fire HD10 Bose Bluetooth HeadSet


Operation allowed during Iteration
Another key difference between ListIterator and Iterator class comes from the fact that you can perform lot of modification operation using ListIterator e.g. you can add element, you can change element and you can remove element using add()set() and remove() method, but you can only remove objects using Iterator interface as it only got the remove() method. See chapter 19 and 20 of Big Java: Early Objects by Cay S. Horstmann to learn more about how to add elements while iterating over ListIterator in Java.

5 Difference between Iterator and ListIterator in Java



Supported Collection classes
Another thing which differentiates Iterator and ListIterator is that Iterator is supported by most of the collection class e.g. ListSetQueue as well as Map which is not a Collection but part of Java's Collection framework. Since Collection class implements the Iterable interface, which defines an iterator() method, all the concrete implementation of Collection classes e.g. ArrayListLinkedListVectorHashSetLinkedHashSetTreeSetPriorityQueue all supports traversal using Iterator.

On the other hand, ListIterator is obtained by calling the listIterator() method which is only defined in the List interface, hence it's only available to concrete implementation of List interface e.g. ArrayList, LinkedList and Vector class. You can read Core Java for Impatient to learn more about these classes and Java Collection framework.


Iteration from any index
One of the unique features of List interface is that it provides another overloaded listIterator(int index) method which can be used to strat traversal from any arbitrary index. Unfortunately, Iterator doesn't support this functionality because it has to operate over collection which doesn't support index-based access e.g. Set and Queue interfaces. Anyway, You can easily write an example of iterating over List starting at a particular index in Java using ListIterator.


Supported Methods
Last difference between Iterator and ListIterator in this list is structural. ListIterator seems to get more feature than Iterator hence got more methods e.g.
hasPrevious() to check whether the list has got more elements while traversing the list in backward direction

next() which returns the next element in the list and moves the cursor forward.

previous() which returns the previous element in the list and moves the cursor backward.

nextIndex() which returns the index of the next element in the list.

previousIndex() which returns the index of the previous element in the list.

remove() to remove the current element in the collection i.e element returned by next() or previous().  See how to remove object using Iterator for more details.

set(E e) to replace the current element i.e element returned by next() or previous() with the specified element, and
add(E e) to insert the specified element in the list


In short, here is a nice summary of differences between ListIterator and Iterator interface in Java:



.