Thursday 2 August 2012

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

    Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements.
    ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

    Example:

      import java.util.*;

      public class Demo {

         public static void main(String args[]) {
            ArrayList al = new ArrayList();
            al.add("A");
            al.add("B");
            al.add("C");
            al.add("D");
            al.add("E");
            al.add("F");

            //iterator 
            System.out.print("Original contents of al: ");
            Iterator itr = al.iterator();
            while(itr.hasNext()) {
               Object element = itr.next();
               System.out.print(element + " ");
            }
            System.out.println();
            
       // listIterator modifying objects
            ListIterator litr = al.listIterator();
            while(litr.hasNext()) {
               Object element = litr.next();
               litr.set(element + "-");
            }

            System.out.print("Modified contents of al: ");

            itr = al.iterator();
            while(itr.hasNext()) {
               Object element = itr.next();
               System.out.print(element + " ");
            }
            System.out.println();

            // Now, display the list backwards
            System.out.print("Modified list backwards: ");
            while(litr.hasPrevious()) {
               Object element = litr.previous();
               System.out.print(element + " ");
             }
             System.out.println();
          }
      }

      output :

      Original contents of al: A B C D E F
      Modified contents of al: A- B- C- D- E- F-
      Modified list backwards: F- E- D- C- B- A-

No comments:

Post a Comment