Wednesday, April 10, 2013

Java ListIterator Example

Java List Iterator Example:

List Iterator is the interface in java.util package.
ListIterator has lot of methods which are very much useful based on our real time scenerios.

ListIterator has methods which we can iterate in the forward / reverse direction.
and ListIterator also have the methods like prviousIndex and nextIndex methods.
and it also has set,remove and add methods.

I am giving the below very basic ListIterator Sample.

 Java List Iterator sample code :


import java.util.ArrayList;
import java.util.ListIterator;

/*
 * Java ListIterator Example
 */
public class JavaListIteratorExample {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {

        // Storing the elements into the arraylist.
        ArrayList aList = new ArrayList();
        aList.add("val-1");
        aList.add("val-2");
        aList.add("val-3");

        // Retrieving the elements from the ArrayList by using ListIterator
        ListIterator listIterator = aList.listIterator();

        String value = "";
        System.out.println("List Iterator in the forward direction");
        while (listIterator.hasNext()) {
            value = (String) listIterator.next();
            System.out.println(value);
        }
        System.out.println("List Iterator in the Reverse direction");
        while (listIterator.hasPrevious()) {
            value = (String) listIterator.previous();
            System.out.println(value);
        }
        System.out.println("List Iterator Previous Index : "
                + listIterator.previousIndex());
        System.out.println("List Iterator Next Index : "
                + listIterator.nextIndex());
    }

}



Output of the above code ;

List Iterator in the forward direction
val-1
val-2
val-3
List Iterator in the Reverse direction
val-3
val-2
val-1
List Iterator Previous Index : -1
List Iterator Next Index : 0



0 comments:

Post a Comment

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.