Friday, 21 June 2013

Iterator Interface in JAVA

Iterator enables us to cycle through a collection, obtaining or removing elements.The iterator() method of the Collection interface returns and Iterator.

For example, you might want to display each element,the easiest way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface.

In general, iterator follow the below steps to cycle through the contents of a collections:


  • Obtain an iterator to the start of the collection by calling the collection's iterator( ) method.


  • Set up a loop by making call to hasNext( ) method and iterate the loop as long as hasNext( ) method returns true.


  • Within the loop, obtain each element by calling next( ).


NOTE: For collections that implement List, you can also obtain an iterator by calling ListIterator(We will discuss this in next chapter).

Following are the list of methods available in Iterator Interface:




An Iterator is similar to the Enumeration interface but Iterators differ from enumerations in following way: 

"Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics".

The remove() method is optionally suported by the underlying collection. When called and supported, the element returned by the last next().

Example:

package com.sample.javase.testing;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class SetInterfaceExample {

/**
* @param args
*/
public static void main(String[] args) {

Set<Integer> set1 = new TreeSet<Integer>();
set1.add(new Integer(5));
set1.add(new Integer(6));
set1.add(new Integer(7));
System.out.println(set1);
//using iterator
for (Iterator<Integer> iterator = set1.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println("using iterator"+ integer);
}
}

}

No comments:

Post a Comment