21 Sept 2012

Iterator in java example

Iterator is an interface in the collection framework. Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time.
Iterator gives you the ability to access the collection in forward direction.

It has methods hasNext() and next().
hasNext( ) returns false when the end of the list has been reached. Otherwise it returns true.
obtain each element by calling next( ).

import java.util.*;

public class iteratordemo
{
public static void main(String[] args)
{
List l = new ArrayList();
for (int i = 1; i < 6; i++)
{
l.add(i);
}
Iterator it = l.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

Output :
1 2 3 4 5

0 comments:

Post a Comment