Java : Cursor : ListIterator


List-iterators are applicable for all the list interfaces. It allows to traverse in backward and forward directions both.

Example:

import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.Arrays;

public class CursorTest {
    
    public void listIteratorTest(){
        String[] str={"A","B","C","D","E","F"};
        List<String> list=Arrays.asList(str);
        ArrayList<String> arrayList=new ArrayList<String>(list); //assigned the array of elements to array list.
        System.out.println(arrayList);

        ListIterator<String> listiterator=arrayList.listIterator();
        while (listiterator.hasNext()) {
            String stringValue=(String)listiterator.next();
            if (stringValue=="A") {
                listiterator.set("Z");
            }
            else if(stringValue=="D"){
                listiterator.remove();
            }
            else if (stringValue=="E") {
                listiterator.add("U");
            }
            
        }
        System.out.println(arrayList);

        while (listiterator.hasPrevious()) {
        System.out.println("The previous value of  "+listiterator.previous()+" is situated at index "+listiterator.previousIndex());
        }    
    }
}

Output :

[A, B, C, D, E, F]
[Z, B, C, E, U, F]
The previous value of F is situated at index 4
The previous value of U is situated at index 3
The previous value of E is situated at index 2
The previous value of C is situated at index 1
The previous value of B is situated at index 0
The previous value of Z is situated at index -1

Supported methods of ListIterator :
.hasNext()-Checks if there any next element or not. Return type is boolean.
.next()-Returns the next element from the list. Return type is object.
.nextIndex()-Returns position of next element . Return type is integer.
.hasPrevious()-Checks if there is any previous element present or not. Return type is boolean.
.previous()-Returns the previous element from the list. Return type is object.
.previousIndex()-Returns position of previous element . Return type is integer.
.remove()- Remove the element from the list. Return type is void.
.set(object) -Replace the existing object. Return type is void.
.add(object)-Add the element to the list. Return type is void.