Wednesday 3 April 2013

What is the difference between java.util.Iterator and java.util.ListIterator?


Both iterator and listIterator are used to traverse the list elements one by one. The main difference between iterator and list iterator is that iterator can traverse the elements of list in only forward direction but listIterator can traverse the elements of list in both forward and backward directions. Sometimes in real time environment, we need to go to the previous element of the list purposely so listIterator is very useful in that case.
This can be easily understood with the examples below:

Iterator Example:

import java.util.*;
public class demoIterator
{
    public static void main(String s[])
    {

        ArrayList al  = new ArrayList();
        //Adding Elements to the Arraylist
        al.add("fffff");
        al.add("bbbbb");
        al.add("ddddd");
        al.add("ccccc");
        al.add("aaaaa");
        //Printing all the element of ArrayList
        System.out.println("All Elements in the ArrayList"+al);
        //Traverse the elements in ArrayList one by one with the help of Iterator
        System.out.println("Start traversing elements of list one by one");
        Iterator it = al.iterator();
        while(it.hasNext())
        {
            //In Iterator, List can be only be traversed in forward with Iterator.next();
            System.out.println(it.next());
        }
    }
}

Output of the program:
All Elements in the ArrayList[fffff, bbbbb, ddddd, ccccc, aaaaa]
Start traversing elements of list one by one
fffff
bbbbb
ddddd
ccccc
aaaaa

ListIterator Example:

import java.util.*;
public class demoListIterator
{
    public static void main(String s[])
    {

        ArrayList al  = new ArrayList();
        //Adding Elements to the Arraylist
        al.add("fffff");
        al.add("bbbbb");
        al.add("ddddd");
        al.add("ccccc");
        al.add("aaaaa");
        ListIterator it1 = al.listIterator();
        System.out.println("Start traversing in forward direction");
        while(it1.hasNext())
        {
            //In ListIterator, List can be traversed in both forward and backward direction with Iterator.next() and Iterator.previous();
            System.out.println(it1.next());
        }
        System.out.println("Start traversing in backword direction");
        while(it1.hasPrevious())
        {
            //In ListIterator, List can be traversed in both forward and backward direction with Iterator.next() and Iterator.previous();
           System.out.println(it1.previous());
       }
    }
}

Output of the program:
Start traversing in forward direction
fffff
bbbbb
ddddd
ccccc
aaaaa
Start traversing in backword direction
aaaaa
ccccc
ddddd
bbbbb
fffff

No comments:

Post a Comment