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]

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment