Java Reference
In-Depth Information
return
return this
this
;
// since main class implements both interfaces
}
// -------------------
// Methods of Iterator
// -------------------
/**
* Tell if there are any more elements.
* @return true if not at the end, i.e., if next() will succeed.
* @return false if next() will throw an exception.
*/
@Override
public
public
boolean
boolean
hasNext
() {
return
return
(
index
<
data
.
length
);
}
/** Returns the next element from the data */
@Override
public
public
T
next
() {
iif
(
hasNext
()) {
return
return
data
[
index
++];
}
throw
throw new
new
NoSuchElementException
(
"only "
+
data
.
length
+
" elements"
);
}
/** Remove the object that next() just returned.
* An Iterator is not required to support this interface,
* and we don't.
* @throws UnsupportedOperationException unconditionally
*/
@Override
public
public
void
void
remove
() {
throw
throw new
new
UnsupportedOperationException
(
"This demo Iterator does not implement the remove method"
);
}
}
The comments on the
remove()
method remind me of an interesting point. This interface in-
troduces
java.util
's attempt at something Java doesn't really have, the “optional method.”
Because there is no syntax for this, and they didn't want to introduce any new syntax, the de-
velopers of the Collections Framework decided on an implementation using existing syntax.
If they are not implemented, the optional methods are required to throw an
Unsuppor-