dsa

Java ListIterator

In this tutorial, we will learn about the Java ListIterator interface with the help of an example.

The ListIterator interface of the Java collections framework provides the functionality to access elements of a list.
It is bidirectional. This means it allows us to iterate elements of a list in both the direction.

It is only applicable for List collection implemented classes like arraylist, linkedlist etc. It provides bi-directional iteration.
ListIterator must be used when we want to enumerate elements of List. This cursor has more functionality(methods) than iterator.
ListIterator object can be created by calling listIterator() method present in List interface.

iterator

Example:

// Java program to demonstrate ListIterator 
import java.util.ArrayList; 
import java.util.ListIterator; 

public class Test 
{ 
	public static void main(String[] args) 
	{ 
		ArrayList al = new ArrayList(); 
		for (int i = 0; i < 10; i++) 
			al.add(i); 

		System.out.println(al); 

		// at beginning ltr(cursor) will point to 
		// index just before the first element in al 
		ListIterator ltr = al.listIterator(); 

		// checking the next element availabilty 
		while (ltr.hasNext()) 
		{ 
			// moving cursor to next element 
			int i = (Integer)ltr.next(); 

			// getting even elements one by one 
			System.out.print(i + " "); 

			// Changing even numbers to odd and 
			// adding modified number again in 
			// iterator 
			if (i%2==0) 
			{ 
				i++; // Change to odd 
				ltr.set(i); // set method to change value 
				ltr.add(i); // to add 
			} 
		} 
		System.out.println(); 
		System.out.println(al); 
	} 
}


output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 1 2 3 4 5 6 7 8 9 
[1, 1, 1, 3, 3, 3, 5, 5, 5, 7, 7, 7, 9, 9, 9]

Methods in Java list Iterator Interface

-
Methods Description
hasNext() returns true if there exists an element in the list
next() returns the next element of the list
nextIndex() returns the index of the element that the next() method will return
previous() returns the previous element of the list
previousIndex() returns the index of the element that the previous() method will return
remove() removes the element returned by either next() or previous()
set() replaces the element returned by either next() or previous() with the specified element