If we want to get object one by one from the collection then we should go for cursor. There are three types of cursor
We can use Enumeration to get object one by one from legacy collection object. We can create Enumeration object by using elements() of Vector class.
Programimport java.util.*; public class EnumerationCursorDemo { public static void main(String[] args) { Vector v=new Vector(); for(int i=0;i<=10;i++) { v.addElement(i); } System.out.println(v); Enumeration e=v.elements(); while(e.hasMoreElements()) { Integer in =(Integer)e.nextElement(); if(in%2==0) System.out.println(in); } System.out.println(v); } }O/P
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0 2 4 6 8 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator is a collection framework interface defined in java 1.2.It is a cursor object used to retrieve element from all collection type objects List, Set & Queue including Vector. It is an alternative of Enumeration object & replacement of "for" loop on collection objects.
By using Iterator we can perform both read/remove operation.
In collection interface, we have below method to obtain iterator object.
public Iterator iterator()Program
import java.util.*; public class IteratorCursorDemo { public static void main(String[] args) { ArrayList al=new ArrayList(); for (int i = 1; i <= 10; i++) { al.add(i); } System.out.println(al); Iterator itr=al.iterator(); while (itr.hasNext()) { Integer in= (Integer)itr.next(); if(in%2==0) System.out.println(in); else itr.remove(); } System.out.println(al); } }O/P
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 2 4 6 8 10 [2, 4, 6, 8, 10]
import java.util.*; public class ListIteratorCursorDemo { public static void main(String[] args) { LinkedList ll=new LinkedList(); ll.add("A"); ll.add("B"); ll.add("C"); ll.add("D"); System.out.println(ll); ListIterator ltr=ll.listIterator(); while (ltr.hasNext()) { String s=(String)ltr.next(); if(s.equals("U")) ltr.remove(); else if(s.equals("N")) ltr.add("W"); else if(s.equals("B")) ltr.set("M"); } System.out.println(ll); } }O/P
[A, B, C, D] [A, M, C, D]