As we know Java has four cursors: Enumeration, Iterator, ListIterator, and Spliterator. We have already discussed Enumeration and Iterator cursors in my previous post. Before going through this post, please go through my previous post at: Java Iterator. In this post, we will discuss about third Java cursor: ListIterator.
Like Iterator, ListIterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object.
NOTE:- What is CRUD operations in Collection API?
In Java, ListIterator is an interface in Collection API. It extends Iterator interface. To support Forward and Backward Direction iteration and CRUD operations, it has the following methods. We can use this Iterator for all List implemented classes like ArrayList, CopyOnWriteArrayList, LinkedList, Stack, Vector, etc. We will explore these methods in-depth with some useful methods in the coming sections.
Java ListIterator interface has the following Methods.
We will explore these methods one-by-one with useful examples in the coming sections.
In this section, we will discuss some ListIterator methods with some examples. First, we need to understand about how to get this iterator object. How to get ListIterator?
ListIterator<E> listIterator()
It returns a list iterator over the elements in this list. Example:-
import java.util.*;
public class ListIteratorDemo
{
public static void main(String[] args)
{
List<String> names = new LinkedList<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting ListIterator
ListIterator<String> namesIterator = names.listIterator();
// Traversing elements
while(namesIterator.hasNext()){
System.out.println(namesIterator.next());
}
// Enhanced for loop creates Internal Iterator here.
for(String name: names){
System.out.println(name);
}
}
}
Output:-
Rams
Posa
Chinni
In section, we will explore how ListIterator’s methods work to perform Forward Direction and Backward Direction iterations.
import java.util.*;
public class BiDirectinalListIteratorDemo
{
public static void main(String[] args)
{
List<String> names = new LinkedListt<>();
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// Getting ListIterator
ListIterator<String> listIterator = names.listIterator();
// Traversing elements
System.out.println("Forward Direction Iteration:");
while(listIterator.hasNext()){
System.out.println(listIterator.next());
}
// Traversing elements, the iterator is at the end at this point
System.out.println("Backward Direction Iteration:");
while(listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
}
}
Output:-
Forward Direction Iteration:
Rams
Posa
Chinni
Backward Direction Iteration:
Chinni
Posa
Rams
As we know Java has four cursors: Enumeration, Iterator, ListIterator, and Spliterator. We can categorize them into two main types as shown below:
As we know, Java ListIterator works in both directions that mean it works in the forward direction as well as backward direction. It is a Bi-directional Iterator. To support this functionality, it has two sets of methods.
In my previous post, we have already discussed how an Iterator works internally in forwarding Direction at “How Java Iterator Works Internally?” section. Even ListIterator also works in that same way. If you want go through my previous post, please click here: Java Iterator. In this section, we will discuss how ListIterator works in Backward Direction. Let us take the following LinkedList object to understand this functionality.
List<String> names = new LinkedList<>();
names.add("E-1");
names.add("E-2");
names.add("E-3");
.
.
.
names.add("E-n");
Now create a ListIterator object on LinkedList as shown below:
ListIterator<String> namesIterator = names.listLterator();
Let us assume “namesIterator” ListIterator looks like below: Here ListIterator’s Cursor is pointing to the before the first element of the List. Now we run the following code snippet in the while loop.
namesIterator.hasNext();
namesIterator.next();
When we run the above code snippet in the while loop, ListIterator’s Cursor points to the last element in the LinkedList. Then we can run the following code snippet to start traversing from the end to the start.
namesIterator.hasPrevious();
namesIterator.previous();
When we run the above code snippet, ListIterator’s Cursor points to the “Last but one” element in the List as shown in the above diagram. Do this process to reach the ListIterator’s Cursor to the first element of the LinkedList. After reading the first element, if we run the below code snippet, it returns “false” value.
namesIterator.hasPrevious();
As ListIterator’s Cursor points to the before the first element of the LinkedList, hasPrevious() method returns a false value. After observing all these diagrams, we can say that Java ListIterator supports Both Forward Direction and Backward Direction Iterations as shown in the below diagrams. So it is also known as Bi-Directional Cursor. Forward Direction ListIterator Backward Direction ListIterator
Unlike Iterator, ListIterator has the following advantages:
Compare to Iterator, Java ListIterator has many advantages. However, it still have the following some limitations.
In this section, we will discuss about Similarities between Java two Cursors: Iterator and ListIterator.
In this section, we sill discuss differences between Java Two Iterators: Iterator and ListIterator.
Iterator | ListIterator |
---|---|
Introduced in Java 1.2. | Introduced in Java 1.2. |
It is an Iterator for whole Collection API. | It is an Iterator for only List implemented classes. |
It is an Universal Iterator. | It is NOT an Universal Iterator. |
It supports only Forward Direction Iteration. | It supports both Forward and Backward Direction iterations. |
It’s a Uni-Directional Iterator. | It’s a Bi-Directional Iterator. |
It supports only READ and DELETE operations. | It supports all CRUD operations. |
We can get Iterator by using iterator() method. | We can ListIterator object using listIterator() method. |
That’s all of about ListIterator in Java. I hope these Java ListIterator theories and examples will help you in getting started with ListIterator programming. Reference: ListIterator API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
The explanation of ListIterator is wrong at ListIterator.hasPrevious() section. You are telling that after executing namesIterator.hasPrevious(); namesIterator.previous(); The cursor will point to last element in the linked list but it is wrong. When you execute this statement you gill get runTimeException as NoSuchElementException. This is because after calling listIterator() function, the cursor will point at the first element of the list. If we want the cursor to point to the last element of List, explicitly we have to iterate throughout the list to reach end of the list, after that we would be able to point to last element of list.
- Vikas Kumar
Hi The below line of code does not go infinite loop. Can anyone explain why? ArrayList arrayList = new ArrayList(); arrayList.add(12); ListIterator listIterator = arrayList.listIterator(); while(listIterator.hasNext()){ Integer input =listIterator.next(); System.out.println(input);//Prints 12 listIterator.add(input+1); }
- Praveen
Eventhough, we add one element via listIterator to arrayList during iteration, it will not go infinite loop. Can anyone explain logic? ArrayList arrayList = new ArrayList(); arrayList.add(12); ListIterator listIterator = arrayList.listIterator(); while(listIterator.hasNext()){ Integer input =listIterator.next(); System.out.println(input);//Prints 12 listIterator.add(input+1); }
- Praveen
Bi-Directional Iterators They are Cursors which supports Both Forward Direction and Backward Direction iterations. For instance, ListIterator are *****Bi******-Directional Iterators.
- Kiran
Very nicely explained. Thank you.
- Biswajit Sahu
Thanks a lot for good explanation.
- Naga