Java Reference
In-Depth Information
As you saw in the previous chapter, the Iterator<T> interface declares three methods: next() ,
hasNext() , and remove() .
NOTE Don't confuse the Iterable<T> interface with the Iterator<T> interface. Iter-
able<T> defines a method that returns a reference of type Iterator<T>; in other words, a
class that implements Iterable<T> can make an iterator available. Iterator<T> defines the
methods that enable the iterator mechanism.
Calling the next() method for an iterator returns successive objects from the collection starting with the
first, so you can progress through all the objects in a collection very easily with a loop such as the following:
MyClass item; // Stores an object from the collection
while(iter.hasNext()) { // Check that there's another
item =; // Retrieve next object
// Do something with item...
This fragment assumes that iter is of type Iterator<MyClass> and stores a reference to an object ob-
tained from whatever collection class you were using.
Most collection classes provide an iterator() method that returns an iterator for the current contents
of the collection. The next() method returns an object as the original type so there's no need for casting.
As long as the hasNext() method returns true , there is at least one more object available from the iterator.
When all the objects have been accessed, the hasNext() method will return false . You must obtain a new
Search WWH ::

Custom Search