Skip to Content
Java in a Nutshell, 5th Edition
book

Java in a Nutshell, 5th Edition

by David Flanagan
March 2005
Intermediate to advanced
1254 pages
104h 21m
English
O'Reilly Media, Inc.
Content preview from Java in a Nutshell, 5th Edition

Name

Iterator<E>

Synopsis

This interface defines methods for iterating, or enumerating, the elements of a collection. It has been made generic in Java 5.0 and the type variable E represents the type of the elements in the collection. The hasNext( ) method returns true if there are more elements to be enumerated or false if all elements have already been returned. The next( ) method returns the next element. These two methods make it easy to loop through an iterator with code such as the following:

for(Iterator i = c.iterator( ); i.hasNext( ); )
    processObject(i.next( ));

In Java 5.0, collections and other classes that can return an Iterator implement the java.lang.Iterable interface, which allows them to be iterated much more simply with the for/in looping statement.

The Iterator interface is much like the Enumeration interface. In Java 1.2, Iterator is preferred over Enumeration because it provides a well-defined way to safely remove elements from a collection while the iteration is in progress. The remove( ) method removes the object most recently returned by next( ) from the collection that is being iterated through. Note, however, that support for remove( ) is optional; if an Iterator does not support remove( ), it throws a java.lang.UnsupportedOperationException when you call it. While you are iterating through a collection, you are allowed to modify the collection only by calling the remove( ) method of the Iterator. If the collection is modified in any other way while an ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java in a Nutshell, 8th Edition

Java in a Nutshell, 8th Edition

Benjamin J. Evans, Jason Clark, David Flanagan
Java in a Nutshell, 7th Edition

Java in a Nutshell, 7th Edition

Benjamin J. Evans, David Flanagan
Learning Java, 5th Edition

Learning Java, 5th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck
Learning Java, 4th Edition

Learning Java, 4th Edition

Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 0596007736Supplemental ContentErrata Page