Java ListIterator is an Interface to iterate over a List in both directions, allowing element modification and index-based operations. In this article, we will discuss what JavaListIterator method is, its implementation, and its advantages and disadvantages. We will also discuss some must-read frequently asked questions for a better understanding of Java ListIterator Method.
What is ListIterator in Java
List Iterator is a sub-interface of the Iterator that can be used to iterator over the elements of the lists. By using List Iterator, Traversal can be done bi-directional (reverse or forward direction). This Iteration can be done to perform the operations such as searching, inserting, deleting, and accessing the elements. You can create an iterator object by calling the iterator() method present in the Collection interface.
Syntax of ListIterator in Java
Iterator itr = CollectionObject.iterator(); Methods in Iterator:
hasNext(): If an element exists in the list, the function hasNext() returns true.
next(): The function next() returns the list's next entry.
remove(): The remove() function removes the last element that the Iterator returns.
public class Main{ public static void main(String[] args){
/*Create an ArrayList class object with object of integer type */ ArrayList<Integer> arr = new ArrayList<Integer>();
/* Iterate or traverse over the list */ for (int i = 0; i < 10; i++) arr.add(i); System.out.println(arr);
/* The cursor, itr, will initially point to index just before the first element in arraylist */ Iterator<Integer> itr = arr.iterator();
/* Iterating till the boolean hasNext() method returns true and print the next element by iterating the list */ while (itr.hasNext()) { /* cursor moves to the next element */ int next = itr.next(); System.out.print(next + " "); } } }
Explanation The iterator ‘itr’ initially points to the index just before the first element in arraylist. We iterate till the boolean hasNext() method returns true and we print the next element by iterating the list.
What is Java List Iterator?
ListIterator is a Java iterator that can be used to iterate across ArrayList, Vector, LinkedList, Stack, and other list types. It has been available since Java 1.2. The Listiterator extends the iterator interface and allows for both forward and backward traversal or bi-directional traversal. It supports - Create, Read, Update, and Delete, which are all four CRUD operations.
There are some functionalities that Java List Iterator provides for better implementation, such as Bidirectional Iteration, Indexed-based Acess, Element Modification, Efficient Manipulation, and Supported List Implementation. We can have more control over iteration on elements if we use List Iterator. While using List Iterator, we should take care of some exceptions that can occur, like ConcurrentModificationException, NoSuchElementException, IllegalStateException, and UnsupportedOperationException.
ListIterator is a bi-directional iterator. For this functionality, it has two kinds of methods:
Forward Direction Iteration
Backward Direction Iteration
1. Forward Direction Iteration:
hasNext(): If an element exists in the list, the function hasNext() returns true.
next(): The function next() returns the list's next entry.
nextIndex(): The nextIndex() function returns the element's index that will be returned by the next() method.
2. Backward Direction Iteration:
hasPrevious(): When the list has more elements to traverse in the backward direction than in the forward way, the hasPrevious() method returns true.
previous(): The function previous() retrieves the list's previous entry.
previousIndex(): the element's index that the previous() method would return is returned by the previousIndex() function.
You may refer to the Iterator vs ListIterator to know more about the difference between Iterator and ListIterator.
Implemenation of ListIterator
1. Forward Direction Iteration
In this Iteration, elements are moved and assessed in the forward direction.
Functions used in Forward Direction Iteration :
hasNext(): If the list contains elements in the forward direction, it returns true.
next(): It returns the next element of the list.
next index(): It returns the index of next element after calling the next().
Example:
Java
Java
import java.util.*; public class CodingNinjas { public static void main(String[] args) {
List<String> words = new LinkedList<>(); words.add("I"); words.add("AM"); words.add("CODER"); ListIterator<String> listIterator = words.listIterator(); System.out.println(listIterator.nextIndex()); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } } }
Output:
0
I
AM
CODER
2. Backward Direction Iteration
In this Iteration, elements are moved and assessed in the backward direction.
Functions used in Backward Direction Iteration :
hasPrevious(): If the list contains elements in the backward direction, it returns true.
previous(): It returns the previous element of the list.
previous index(): It returns the previous index returned by the previous() function.
Example:
Java
Java
import java.util.*; public class CodingNinjas { public static void main(String[] args) { List<String> words = new LinkedList<>(); words.add("I"); words.add("AM"); words.add("CODER"); ListIterator<String> listIterator = words.listIterator(); while (listIterator.hasNext()) { listIterator.next(); } System.out.println(listIterator.previousIndex()); while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); } } }
Output
2
CODER
AM
I
ArrayList listIterator() Method in Java
The Java ArrayList's listIterator () method returns an iterator across the list's elements beginning at the specified position. The first element that would be returned by next() is given by the specified index. When previous() is first called, it returns the element at the specified index minus one.
Syntax:
public ListIterator<E> listIterator(int index);
Parameter: When calling the iterator.next() method, "index" refers to the index of the first element that will be returned from the list iterator.
Return value: By starting at the specified position in the list, this method returns a list iterator across the elements in the list (in the correct order).
Exception: The iterator throws IndexOutOfBoundsException if the index is out of range, i.e., index < 0 or index > size of the list.
Examples of ArrayList listIterator() Method in Java
Let’s see examples describing iteration methods of the ListIterator interface in an array list.
int prevNumber = iter.previous(); System.out.println("Previous Element is: " + prevNumber );
int prevIndex = iter.previousIndex(); System.out.println("Index of Previous Element: " + prevIndex );
boolean hasPrev = iter.hasPrevious(); System.out.println("Does the array have any previous element? " + hasPrev); } }
Output:
Explanation
Initially, the cursor lies before the first element of the array list. After calling the next() method, the iterator instance will be between 10 and 11 and thus 10 is printed as the next element. The index is thus printed as 1. Since the array list contains elements ahead of the next() method, thus the boolean hasNext() returns true. Now, the next() method has been called 4 times. Thus now the instance of the iterator method will be between 14 and 15. Thus previous() returns 14 and so the index is returned as 3. Since the array list contains elements before the iterator instance, the boolean hasPrevious() returns true.
The instance “iter” is positioned at the index 6 of the array list, which is the last index of the list. The boolean hasNext() will return false as there is no next element in the array. The iterator “iter1” throws IndexOutOfBoundsException error since it is trying to access the index which exceeds the array size.
LinkedList listIterator() Method in Java
The Java.util.LinkedList.listIterator() method returns a list iterator with the same elements as the LinkedList and in the same order beginning at a particular location or index number as the LinkedList. The function receives the position or index as a parameter.
The iterator “iter” is positioned on specified index 3 of the list, which means the cursor now points to the index 3. Now we iterate the list till the boolean hasNext() holds true. Thus, the output is given as 13 14 15, since the iter starts from index 3 of the list.
Advantages and Disadvantages of Java List Iterator
Advantages:
The four CRUD operations—Create, Read, Update, and Delete—are supported.
It allows forward and backward iteration in both directions or bi-directional traversal.
Using simple method names is simple.
Disadvantages:
This iterator supports only list implementation classes.
All collection APIs are not covered by it.
The list Iterator does not allow for element iteration in parallel.
Iterator v/s ListIterator
Iterator and ListIterator are the Interfaces in Java that are used to iterate the elements in the collection or the list.
Iterator is an interface in Java that provides a way to iterate the elements in the collection. There are some methods, such as hasNext(), next(), and remove(), that can be used while doing an iteration using the Iterator interface.
ListIterator is a sub-interface of Iterator that extends the functionality of Iterator to iterate the elements in the list as well. There is support for bi-directional (forward or backward) iteration while using ListIterator. There are some methods, such as hasPrevious(), previous(), and nextIndex(), that can be used while doing an iteration using the ListIterator interface.
Differences Between Iterator and ListIterator
Parameters
Iterator
ListIterator
Iteration Direction
Iteration can be done in only a forward direction.
Iteration can be done bidirectional (forward or backward direction)
Accessing Previous Elements
Iterator methods are very limited and can not access the previous elements in the collection.
ListIterator provides additional methods such as hasPrevious(), previous(), and previousIndex() that can be used to access the previous elements and indexes.
Modification & Insertion
Iterator provides the method remove() for the removal.
ListIterator provides the methods set(E element) and add(E element) for the modification and insertion in the list.
Initial Position While Iterating
In Iterator, the initial position while iterating is before the first element.
In ListIterator, the initial position while iterating is between the first and second elements.
Similarities between Iterator and ListIterator
Iterator and ListIterator can be used to iterate the elements in the collection.
To check the next element in the collection, Iterator and ListIterator can use the hasNext() method.
To check the previous element in the collection, Iterator and ListIterator can use the hasPrevious() method.
To remove the element, Iterator and ListIterator can use the remove() method.
Frequently Asked Questions
How to iterate list in Java 11?
There are some methods by which the list can be iterated:
Enhanced for loop can be used: for(Integer num: list)
for loop with the indexing can be used: for(int i = 0; i < list.size(); i++)
The iterator interface can be used: Iterator<Integer> iterator = list.iterator()
What is the significance of ListIterator?
ListIterator is a Java interface that enables you to traverse a List in both forward and backward directions, as well as make changes to the List while iterating. It has more functionality than a regular Iterator and is helpful for performing complex List manipulations.
When to use list Iterator in Java?
ListIterator is useful when you need to modify the list during the time of iteration, like inserting or removing at specific positions and when the traversal of the list in both forward and backward directions is being done.
Which iterator can be used only with list?
The ListIterator interface can be used only with Lists, as it provides methods to traverse a List bidirectionally and perform modifications to the List during iteration.
Why do we use list Iterator in Java?
We use a list iterator in Java to traverse and manipulate elements in a list. It's like a guided tour through a list, allowing us to move forward and backward, remove items, or add new ones easily.
Conclusion
In this article, we explored the Java list iterator. We explored examples related to the Java list iterator and how it works with array list and linked list. We also studied its pros and cons. We believe this article on Java list iterator was helpful. To learn more about Java Iterators, check out our articles on