Java Reference
In-Depth Information
tedOperationException
if they ever get called. My
remove( )
method does this. Note that
UnsupportedOperationException
is subclassed from
RuntimeException
, so it is not re-
quired to be declared or caught.
This code is unrealistic in several ways, but it does show the syntax and demonstrates how
the
Iterator
interface works. In real code, the
Iterator
and the data are usually separate
objects (the
Iterator
might be an inner class from the data store class). Also, you don't
even need to write this code for an array; you can just construct an
ArrayList
object, copy
the array elements into it, and ask it to provide the
Iterator
. However, I believe it's worth
showing this simple example of the internals of an
Iterator
so that you can understand both
how it works and how you could provide one for a more sophisticated data structure, should
the need arise.
The
Iterable
interface has only one nondefault method,
iterator()
, which must provide
an
Iterator
for objects of the given type. Because the
ArrayIterator
class implements
this as well, we can use an object of type
ArrayIterator
in a “foreach” loop:
structure/ArrayIteratorDemo.java
package
package
structure
;
import
import
com.darwinsys.util.ArrayIterator
com.darwinsys.util.ArrayIterator
;
public
public class
class
ArrayIteratorDemo
ArrayIteratorDemo
{
private
private final
static
String
[]
names
= {
"rose"
,
"petunia"
,
"tulip"
final static
};
public
public static
void
main
(
String
[]
args
) {
ArrayIterator
<
String
>
arrayIterator
=
new
static
void
new
ArrayIterator
<>(
names
);
// Java 5, 6 way
for
for
(
String s
:
arrayIterator
) {
System
.
out
.
println
(
s
);
}
// Java 8 way
arrayIterator
.
forEach
(
s
->
System
.
out
.
println
(
s
));
}
}