Java Reference
In-Depth Information
You may not know what class the
iteratorForC
is an instance of, but you do know
it satisfies the
Iterator<String>
interface, so you know it has the methods in the
Iterator<T>
interface. These methods are given in Display 16.12.
Display 16.13 contains a simple demonstration of using an iterator with a
HashSet<T>
object. A
HashSet<T>
object imposes no order on the elements in the
HashSet<T>
object, but the iterator imposes an order on the elements—namely,
the order in which they are produced by
next()
. There are no requirements on this
ordering. If you run the program in Display 16.13 twice, the order of the elements'
output will almost certainly be the same each time. However, it would not be an error
if they are output in a different order each time the program runs.
If the collection used with an
Iterator<T>
imposes an order on its elements,
such as an
ArrayList<T>
does, then the
Iterator<T>
will output the elements in
that order. If you require an order with a
HashSet<T>
object, then you may use the
LinkedHashSet<T>
class, which uses an internal doubly linked list to store the items in
the order that they are added.
Display 16.12
Methods in the
Iterator<T>
Interface
The
Iterator<T>
interface is in the
java.util
package.
All the exception classes mentioned are the kind that are not required to be caught in a
catch
block or declared in a
throws
clause.
NoSuchElementException
is in the
java.util
package, which requires an import statement
if your code mentions the
NoSuchElementException
class. All the other exception classes
mentioned are in the package
java.lang
and so do not require any import statement.
public
T next()
Returns the next element of the collection that produced the iterator.
Throws a
NoSuchElementException
if there is no next element.
public boolean
hasNext()
Returns
true
if
next()
has not yet returned all the elements in the collection; returns
false
otherwise.
public void
remove() (
Optional
)
Removes from the collection the last element returned by
next
.
This method can be called only once per call to
next
. If the collection is changed in any way,
other than by using
remove
, the behavior of the iterator is not specified (and thus should be
considered unpredictable).
Throws
IllegalStateException
if the
next
method has not yet been called, or if the
remove
method has already been called after the last call to the
next
method.
Throws an
UnsupportedOperationException
if the
remove
operation is not supported by
this
Iterator<T>
.