Thursday, June 24, 2021

5 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 mean 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() methods to access the next and previous elements from the List.

Unfortunately, ListIterator only supports the List interface, you cannot use it to traverse over Map or Set in Java. That was the basic difference between Iterator and ListIterator class, let's see a couple of more to answer this question in detail on the Java interviews.


Iterator vs ListIterator

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

Let's see each of them in a little bit of detail:




1. Traversal direction

As I told you in the first paragraph the fundamental difference between Iterator and ListIterator is that the former allows traversal only in the forward direction i.e. you cannot go back once you move forward, which is what sometimes you need. ListIterator gives you that functionality via the previous() method. 

Similar to next() this method returns the previous element hence support traversal in the backward direction, you can further check Java Programming Masterclass for Software Developers course on Udemy to learn more about Iterating over Collections in Java. 

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.
 *
 * @author Javin Paul
 *
 */
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


2. Operations allowed during Iteration

Another key difference between ListIterator and Iterator class comes from the fact that you can perform a lot of modification operation using ListIterator like you can add an element, you can change element and you can remove an element using add(), set() and remove() method, but you can only remove objects using Iterator interface as it only got the remove() method. 

You can also see chapters 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



3. Supported Collection classes

Another thing that differentiates Iterator and ListIterator is that Iterator is supported by most of the collection classes like List, Set, Queue as well as Map which is not a Collection but part of Java's Collection framework. 

Since the Collection class implements the Iterable interface, which defines an iterator() method, all the concrete implementation of Collection classes like ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue all support 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 the concrete implementation of List interface like ArrayList, LinkedList, and Vector class. 

You can also join Java Collections from basics to Advanced course on Udemy to learn more about these classes and the Java Collection framework.

Iterator vs ListIterator in Java



4. Iteration from any index

One of the unique features of the List interface is that it provides another overloaded listIterator(int index) method which can be used to start traversal from any arbitrary index. 

Unfortunately, Iterator doesn't support this functionality because it has to operate over the collection which doesn't support index-based access like Set and Queue interfaces. 

Anyway, You can easily write an example of iterating over List starting at a particular index in Java using ListIterator.


5. Supported Methods

The last difference between Iterator and ListIterator in this list is structural. ListIterator seems to get more features than Iterator hence got more methods like the hasPrevious() to check whether the list has got more elements while traversing the list in the 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.
  • add(E e) to insert the specified 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().  You can also see how to remove objects 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

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

ListIterator vs Iterator in Java


That's all about the difference between Iterator and ListIterator in Java. The main advantage of Iterator is that your code will work even if you pass a List or Set because you will be working with a Collection, but when you use the ListIterator, then your code will only work with the List.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures and Algorithms: Deep Dive Using Java

Other Java Collection articles you may like to explore
  • Difference between fail-safe and fail-fast Iterator in Java? (answer)
  • Difference between Hashtable and HashMap in Java? (answer)
  • Difference between TreeMap and TreeSet in Java? (answer)
  • Difference between ArrayList and LinkedList in Java? (answer)
  • Difference between HashMap and LinkedHashMap in Java? (answer)
  • Difference between EnumMap and HashMap in Java
  • Difference between ArrayList and HashSet in Java? (answer)
  • Difference between HashSet and TreeSet in Java? (answer)
  • Difference between HashMap and ConcurrentHashMap in Java? (answer)
  • Difference between Vector and ArrayList in Java? (answer)
  • Difference between IdentityHashMap, WeakHashMap, and EnumMap in Java? (answer)

Thanks for reading this article so far. If you like my explanation of Iterator vs ListIterator in Java then please share this article with your friends and colleagues. If you have any questions or feedback, please drop a note. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.