Monday, February 23, 2009

sample code to demonstrate Iterator



package collection;

import java.util.ArrayList;
import java.util.Iterator;

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

}

}


output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
2
4
6
8



0 comments:

Post a Comment