*cursors of collection frame work: This cursors are used to Access the elements one by one and perform some other operations. They are 3 cursors and they are:

 1. Iterator:
This cursor can be applied to all the collection classes and it can be used to accesses the elements in forward direction only.
2.ListIterator:
This cursor can be applied to all the List implementation classes and it can be used to accesses the element and both forward and backward direction.
(Arraylist,Linkedlist,Vector);

 3.Enumeration:
This cursor can be applied to only the legacy classes and it can be used to accesses the elements in forward direction only. It can be only legacy interfaces.

example:

import java.util.*;

 public class IteratorDemo {
 public static void main(String args[]) {
 // Create an array list

 ArrayList al = new ArrayList();

 // add elements to the array list

 al.add("C");
 al.add("A");
 al.add("E");
 al.add("B");
 al.add("D");
 al.add("F");
 // Use iterator to display contents of al

 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();

 // Modify objects being iterated

 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();
 }
}

Download for Source Code Click Here

0 comments:

Post a Comment