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().
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.
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 Iteratorfrom 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:
Taking user input:
Forward traversal using iterator:
Forward and Backward traversal using 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-------"); } }
You can also try this code with Online Java Compiler
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()); } } }
You can also try this code with Online Java Compiler
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: