Pages

ListIterator in java

What is ListIterator in java?

ListIterator(I):: By using list iterator either we can move to the forward direction or to the backward direction and hence it is a bi-directional cursor.

---> By using list iterator we can perform replacement and addition of new objects in addition to read and remove operations

---> we can create iterator object by using the ListIterator() method of List interface.

public ListIterator listIterator()

ex:: ListIterator lt=l.listiterator(); --- where l is any List object



Java ListIterator
Java ListIterator()
Methods:: ListIterator is the child interface of Iterator(I). Hence all methods present in Iterator by default available in List iterator.

Java ListIterator
ListIterator
ListIterator defines the following 9 methods:

public boolean hasNext()
public object next()
public int nextIndex()

public boolean hasPrevoious()
public object previous()
public int previousIndex()

public void remove()
public void set(Object new)
public void add(Obejct new)

Demo on ListIterator program:
import java.util.ArrayList;
import java.util.ListIterator;
public class CursorsDemo {
    public static void main(String[] args) {
        ArrayList l = new ArrayList();
        l.add(1);
        l.add(3);
        l.add(2);
        l.add(5);
        l.add(0);
        ListIterator Itr = l.listIterator();
        while (Itr.hasNext()) {
            Integer I = (Integer) Itr.next();
            if (I.equals(3)) {
                Itr.remove();
            }
            if (I.equals(2)) {
                Itr.add(123);
            }
            if (I.equals(5)) {
                Itr.set(999);
            }
        }
        System.out.println(l);
        if (Itr.hasPrevious()) {
            System.out.println(Itr.previousIndex());
        }
    }
}

Output:
[1, 2, 123, 999, 0]
4

Limitations of Listiterator(I):
The Most powerful cursor is listiterator but its limitation is, it is applicable only for List implemented class objects.
(i.e., not applicable for tree set,hash set etc.,.).Hence it is not a universal cursor.
Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.