Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

ListIterator

  • • By using ListIterator we can move either to the forward direction or to the backward direction, hence ListIterator is bidirectional cursor.
  • • By using ListIterator we can perform replacement and addition of new objects in addition to read and remove operations.
  • • We can create ListIterator object by using listIterator() method of List interface.

    • public ListIterator listIterator();
    ListIterator li=l.listIterator():
    //where l is any List object.

Methods in ListIterator:

  • • ListIterator is the child interface of Iterator, hence all the methods of Iterator by default available in ListIterator.
  • • ListIterator defines the following methods: Forward direction:

    public booleanhasNext();
    public Object next();
    public intnextIndex();

    Backward direction:

    public booleanhasPrevious();
    public Object previous();
    public intpreviousIndex();

    Additional capability methods:

    public void remove();
    public void set(Object new); // for replacement new object
    public void add(Object new);

let's see a simple program to better understand these concepts easily.

Example:
ListIteratorDemo.java
importjava.util.*;
classListIteratorDemo
{
	public static void main(String args[])
	{
		LinkedList l=new LinkedList();
		l.add("Sidhant");
		l.add("Anubhav");
		l.add("Babushan");
		l.add("Arindam");
		System.out.println(l);
		ListIterator li=l.listIterator();
		while(li.hasNext())
		{
			String s=(String)li.next();
			if(s.equals("Arindam"))
			{
				li.remove();
			}
			else
			if(s.equals("Babushan"))
			{
				li.add("Amlan");
			}
			else
			if(s.equals("Anubhav"))
			{
				li.set("Budhaditya");
			}
		}
		System.out.println(l);
	}
}

Output:

[Sidhant, Anubhav, Babushan, Arindam]
[Sidhant, Budhaditya, Babushan, Amlan]

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext