Sunday, February 15, 2009

Iterator,ListIterator,Enumeration

Enumeration:
This is cursor to retrive the objects one by one.
This interface contains the following two methods.
1.boolean hasMoreElements();
2.Object nextElement();
Enumeration Example:
Import java.util.*;
Class EnumDemo
{
public static void main(String arg[])
{
Vector v= new Vector();
For(int i=0;i<=10; i++)
{
v.addElement(new Integer(i);
}
System.out.println(v); // [0,1,2,3…….10]
Enumeration e=v.elements();
While(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
If(i.IntValue() % 2 ==0)
{
System.out.println(i);
}
}
}
Limitations:
1. We can get Enumeration Object only for legacy classes (Vector,Stack,Hashtable,Properties,Dictionary,Enumeration)
2. While iterating the Objects of enumeration we can get only read-access.
i.e while iterating we are not allowed to perform any remove or modify operation.
Iterator:
This can be applied for any collection implemented class (legacy and non-legacy)
While iterating the objects we are allowed to perform remove operation also, in addition to read operation.
This interface contain the following there methods
Boolean hasNext()
Object next();
Void remove()

Iterator Example:
Import java.util.*;
Class IteratorDemo
{
public static void main(String arg[])
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(new Integer(i);
}
System.out.println(i); // 0,1,2,3,……9
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer i=(Integer)itr.next();
If(i.intValue() % 2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(l); [0,2,4,6,8]
}
}
}

List Iterator:
List iterator is the child interface of iterator .this can be applicable only for list implemented classes (arraylist,linkedlist,vector and stack).
This is a bidirectional cursor .we can move either to forward or backward direction
While iterating ,we are allowed to replace existing element with the new element ,we are allowed to add new elements and still we can perform remove operation also.
ListIterator defines the following methods.
1.boolean hasNext();
2.boolean hasPrevious();
3.Object next();
4.Object previous();
5.int nextIndex();
if there is no next element it just simply return the size of the list.
6.int previousIndex()
Return -1 if there is no previous index.
7.void remove()
8.void set()
9.void add()

ListIterator Example:
Import java.util.*;
Class ListIterDemo
{
public static void main(String arg[])
{
LikedList l=new LinkedList();
L.add(“laxman”);
l.add(“chandu”);
l.add(“ravi”);
l.add(“raju”);
System.out.println(l);
ListIterator lt=l.listIterator();
While(lt.hasNext())
{
String s=(String)lt.next();
If(s.equals(“laxman”))
{
lt.remove(); or lt.set(“scjp”);
}
}
System.out.println(l);
}
}

3 comments:

Anonymous said...

Excellent great job please keep it up.
cheers
raky

Anonymous said...

nice one

Anonymous said...

really awesome!!

Post a Comment