Java in a Nutshell, 5th Edition [Electronic resources]

نسخه متنی -صفحه : 1191/ 725
نمايش فراداده

Iterator<E>java.util

Java 1.2

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 iteration is ongoing, the Iterator may fail to operate correctly, or it may throw a ConcurrentModificationException.

public interface

Iterator<E> { // Public Instance Methods boolean

hasNext ( ); E

next ( ); void

remove ( ); }

Implementations

ListIterator, Scanner

Returned By

Too many methods to list.