Java Iterator

Java Iterator Print E-mail
Contributed by Joe   
Friday, 14 July 2006

Java Iterator overview

In Java, an iterator is an interface that can be implemented by a collection class. Any collection object can create an object of type Iterator that encapsulates references to all the objects in the original collection in some sequence, and that can be accessed using the Iterator interface methods. In other words an iterator provides an easy way to get at all the objects in a collection one at a time.

Iterator Methods list

Method

Description

next()

Returns an object as type Object starting with the first, and sets the Iterator object to return the next object on the next call of this method. If there is no object to be returned the method throws a NoSuchElementException exception.

hasNext()

Returns true if there is a next object to be retrieved by a call to next().

remove()

Removes the last object returned by next() from the collection that supplied the Iterator object. If next() has not been called or if you call remove() twice after calling next(), an IllegalStateException will be thrown. Not all iterators support this method, in which case an UnsupportedOperationException exception will be thrown if you call it.


 Iterate Example

     // For a set or list
    for (Iterator it=collection.iterator(); it.hasNext(); ) {
        Object element = it.next();
    }
   
    // For keys of a map
    for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
        Object key = it.next();
    }
   
    // For values of a map
    for (Iterator it=map.values().iterator(); it.hasNext(); ) {
        Object value = it.next();
    }
   
    // For both the keys and values of a map
    for (Iterator it=map.entrySet().iterator(); it.hasNext(); ) {
        Map.Entry entry = (Map.Entry)it.next();
        Object key = entry.getKey();
        Object value = entry.getValue();
    }

Question about Iterator

 Given:
11. ArraryList a = new ArrayList();
12. a.add(“Alpha”);
13. a.add(“Bravo”):
14. a.add(“Charlie”);
15. a.add(“Delta”);
16.Iterator iter = a.iterator();
17.

 Which two, added at line 17, print the names in the ArrayList in alphabetical order?
(Choose two)

A.  for (int i=0; i< a.size(); i++) System.out.println(a.get(i)));
B.  for (int i=0; i< a.size(); i++) System.out.println(a[i]);
C.  while( iter.hasNext() ) System.out.println(iter.next()) ;
D.  for (int i=0, i< a.size(); i++) System.out.println(iter[i]);
E.   for (int i=0; i< a.size(); i++) System.out.println(iter.get(i));

Last Updated ( Friday, 14 July 2006 )

  home              contact us

 

©2006-2010 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground