Contents    Page-10    Prev    Next    Page+10    Index   

Java Collections Iteration

Two iterator patterns can be used with collections. The first is a simple iteration through all elements:


for ( AnyType item : coll )

The second form allows more complicated processing, including removal of an item.


Iterator<AnyType> itr = coll.iterator();

while ( itr.hasNext() ) {
  AnyType item = itr.next();
  ...          // process item
  if ( ... )   itr.remove();   }
In this pattern, an iterator object itr is created. This object can be queried to test whether any items remain using itr.hasNext(). If there are objects, itr.next() gets the next one. itr.remove() removes the last object returned by itr.next() and can only be used once until there is another call to itr.next() .

A collection should not be modified while an iteration over it is in progress, except by the itr.remove() .