Saturday, January 9, 2010

Interface Iterator

Categories: , ,

public interface Iterator
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections framework. Iterators differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
This interface is a member of the Java Collections Framework.
Methods:


        1.hasNext

  • public boolean hasNext()
  • Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)
    2.next
public Object next()
Returns the next element in the iteration.
Returns:
the next element in the iteration.
Throws:
NoSuchElementException - iteration has no more elements
3.remove
public void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.
Throws:
UnsupportedOperationException - if the remove operation is not supported by this Iterator.
IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method
Example:









  1. /*
      Iterate through a Collection using Java Iterator Example
  2.   This Java Example shows how to iterate through a Collection using Java Iterator.
  3. */
  4. import java.util.Iterator;
  5. import java.util.ArrayList;
  6. public class JavaIteratorExample {
  7. public static void main(String[] args) {
  8. //create an ArrayList object
  9. ArrayList aList = new ArrayList();
  10. //populate ArrayList object
  11. aList.add("1");
  12. aList.add("2");
  13. aList.add("3");
  14. aList.add("4");
  15. aList.add("5");
  16. /*
  17.       Get Iterator object by invoking iterator method of collection.
  18.       Iterator provides hasNext() method which returns true if has more
  19.       elements. next() method returns the element in iteration.
  20.  */
  21. Iterator itr = aList.iterator();
  22. //iterate through the ArrayList values using Iterator's hasNext and next methods
  23. while(itr.hasNext())
  24. System.out.println(itr.next());
  25. /*
  26.   Please note that next method may throw a java.util.NoSuchElementException
  27.       if iteration has no more elements.
  28.  */
  29. }
  30. }
  31. /*
  32. Output would be
  33. 1
  34. 2
  35. 3
  36. 4
  37. 5
  38. */



Spread The Love, Share Our Article

Related Posts

No Response to "Interface Iterator"

Post a Comment