Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Iterator?
2.1.
Iterator Syntax
3.
What is Listiterator?
3.1.
Listiterator Syntax
4.
Differentiation between Iterator and ListIterator
5.
Methods in Iterator vs ListIterator
5.1.
Dry Run
5.2.
Example for Iterator
5.3.
Java
5.4.
Example for ListiIterator
5.5.
Java
5.6.
Class Diagram for Iterator vs Listiterator
5.7.
Which One to Use?
6.
Frequently Asked Questions
6.1.
What is the connection between the Iterator and ListIterator interfaces?
6.2.
Is Iterator a class or an interface?
6.3.
What is the difference between iterator and ListIterator in Python?
6.4.
What is the difference between iterator and enumerator?
6.5.
What is the main difference between iterator and iterable?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What’s the Difference Between Iterator and ListIterator?

Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Iterator is a general interface for traversing collections that supports forward iteration with next(), while ListIterator is specific to lists and allows bidirectional iteration and it supports both forward and backward iteration with next() and previous().

Introduction

So let's dive into the topic.

What is Iterator?

In a Collection Framework, an Iterator is essentially an interface. An Iterator can be used to navigate the elements of the Collection. You can acquire elements present in the Collection or remove elements from the Collection by using an Iterator to cycle through each element in the Collection one at a time. 

  • The Iterator has a method called Iterator(), which returns the Iterator to the very beginning of the Collection.
     
  • Once you get an Iterator to the very start of a Collection, then to traverse the elements present in the Collection, a loop is established that calls hasNext() each time the loop iterates. 
     
  • If the hasNext() function returns true, the Collection contains the next element; if it returns false, all of the elements have been explored. 
     
  • Next, inside the loop, you can use the next() method to get each element of a Collection. The Collection's next element is returned by the next() method.

Iterator Syntax

import java.util.*;

// Here "x" is any Collection object. 
// "it" is of type Iterator interface and refers to "x"
Iterator it = x.iterator(); 


Iterator vs ListIterator is an exciting topic. Until now, we have discussed only the first component of Iterator vs ListIterator. Let’s proceed to see the next segment of it.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Listiterator?

ListIterator is a Collection framework interface that extends the Iterator interface. ListIterator allows you to traverse the Collection's elements in forward and backward ways. Any Collection component can also be added, removed, or modified. In a nutshell, it eliminates the shortcomings of the Iterator.

Listiterator Syntax

import java.util.*;

// Here "y" is any List object.
// "lit" is of type ListIterator interface and refers to "y"
ListIterator lit = y.listIterator();

Differentiation between Iterator and ListIterator

To make it easy for you to understand Iterator vs listIterator,  the difference between them has been represented in tabular form below:

Property  

Iterator

ListIterator

Direction of Traversal It can traverse elements present in a Collection only in the forward direction. It can traverse elements present in a Collection both in forward and backward directions.
Traverasability It is used to traverse Map, List, and Set. It is used only to traverse List. That is it can’t traverse Map and Set.
Addition of elements Iterator cannot add elements to a Collection. ListIterator can add elements to the Collection.
Modification Possible An Iterator cannot modify the elements in the Collection. A ListIterator can modify the elements in a Collection using a set().
Obtaining Index An Iterator has no method to obtain an index of the element in a given Collection. ListIterator can be used to obtain the index of an element in the Collection.
Methods available It has methods like hasNext(), next(), remove(). It has methods like add(E e), hasNext(), hasPrevious(), next(), nextIndex(), previous(), previousIndex(), remove(), set(E e).

Methods in Iterator vs ListIterator

Methods in Iterator:

  • hasNext() - It returns true if the iteration has more elements.
  • next() - This method returns the next element in the iteration.
  • remove() - This method removes the last element that is returned by the Iterator from the Collection.
     

After Java 17 release, in addition to the above-listed methods, we have four methods in the ListIterator interface that are not found in the Iterator:

  • hasPrevious() - It returns the previous object in an ordered list
  • nextIndex() - It returns the numeric index of the element that is next in the list
  • previousIndex() - It returns the numeric index of the previous element in the ordered list
  • add() - It inserts an object into an ordered list at a specific location

Dry Run

Importing java.util package:

Importing java.util package

Taking user input:

Taking user input

Forward traversal using iterator:

iterator

Forward and Backward traversal using Listiterator:

listiterator

Example for Iterator

The code below explains how to use Iterator with all the important methods available.

Code:

  • Java

Java

// Importing the ArrayList class and the Iterator class
import java.util.*;

public class Main {
 public static void main(String[] args) {

   // Making a collection
   ArrayList < String > countries = new ArrayList < String > ();
   Scanner scanner = new Scanner(System.in);
   
   System.out.print("Enter 5 countries :\n");
   for (int i = 0; i < 5; i++)
   {
     countries.add(scanner.nextLine());
   }
   System.out.println("The countries are:");
   System.out.println(countries);

   // Get the iterator
   Iterator < String > it = countries.iterator();

   // Print the first item using next() method
   System.out.println(it.next());
   System.out.println("Looping through a collection using next() and hasNext() methods");
   
   // Looping through the collection using next() and hasNext() methods
   while (it.hasNext()) {
     System.out.println(it.next());
   }
   
   // Using the remove() method
   it.remove();
   System.out.println("Looping through a collection using next() and hasNext() methods again");
   
   // Looping through the collection after using remove() method
   while (it.hasNext()) {
     System.out.println(it.next());
   }
   System.out.println("-------elements are removed-------");
 }
}


Output:

Output 1

Practice by yourself on java online compiler.

Example for ListiIterator

The code below explains how to use a listIterator.

Code:

  • Java

Java

import java.util.*;

public class Main {
  public static void main(String args[])
  {
   // Making a collection
    ArrayList < String > countries = new ArrayList < String > ();
     Scanner scanner = new Scanner(System.in);
     System.out.print("Enter 5 countries :\n");
       for (int i = 0; i < 5; i++)
       {     
           countries.add(scanner.nextLine());
       }
       System.out.println("The countries are:");
       System.out.println(countries);

    // Getting the ListIterator object.
    ListIterator listIterator = countries.listIterator();

    // Print the ArrayList elements in forward direction.
    System.out.println("ArrayList elements in " + "forward direction:");
    while (listIterator.hasNext()) {
      System.out.println(listIterator.next());
    }

    // Print the ArrayList elements in backward direction.
    System.out.println("ArrayList elements in " + "backward direction:");
    while (listIterator.hasPrevious()) {
      System.out.println(listIterator.previous());
    }
  }
}


Output:

Output 2

Class Diagram for Iterator vs Listiterator

Class diagram for iterator vs listiterator

Which One to Use?

When the underlying Collection class is numerically ordered and at least one of the following three conditions is true, developers should pick the ListIterator over the Iterator:

  • A class is needed to be added to a specific location in the ordered Collection.
  • Backward navigation through an ordered Collection is required.
  • Finding the numerical index of the previous or following element in an ordered Collection is required.

Frequently Asked Questions

What is the connection between the Iterator and ListIterator interfaces?

In Java, an Iterator interface allows us to traverse the elements of a list in the forward direction. In contrast, a ListIterator interface extends the Iterator interface and allows us to traverse the elements in both the forward and backward ways.

Is Iterator a class or an interface?

The Java Iterator is an interface that was introduced in the Java Programming language as part of the Java 1.2 Collection architecture. It is part of Java.util package.

What is the difference between iterator and ListIterator in Python?

The key difference is ListIterator is specific to lists, offering bidirectional traversal and modification, while iterators generally traverse elements one by one in a forward direction from any iterable.

What is the difference between iterator and enumerator?

An iterator is a more general concept for iterating over elements, while an enumerator provides index-value pairs during iteration, common in Python's enumerate() function.

What is the main difference between iterator and iterable?

Iterators are objects that allow iteration over a sequence, while iterables are objects that can be iterated over, such as lists or dictionaries. An iterator is created from an iterable.

Conclusion

In this blog, we have discussed what’s the difference between Iterator and ListIterator. Knowing the difference between Iterator and ListIterator in Java is really important for writing better programs. Iterator is like a general tool for moving through collections, while ListIterator is more specialized for lists and offers extra features. 

To explore more interesting coding-related articles, refer to the following links:

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Keep learning, and Keep Growing!

Happy Learning!

Previous article
Difference Between Iterator and Enumeration
Next article
Association, Composition and Aggregation in Java
Live masterclass