Java Reference
In-Depth Information
Discussion
To make data from one part of your program available in a storage-independent way to other
parts of the code, generate an
Iterator
. Here is a short program that constructs, upon re-
quest, an
Iterator
for some data that it is storing—in this case, in an array. The
Iterator
interface has only three methods—
hasNext()
,
next()
, and
remove()
:
package
package
com
.
darwinsys
.
util
;
import
import
java.util.Iterator
java.util.Iterator
;
import
import
java.util.NoSuchElementException
java.util.NoSuchElementException
;
/** Demonstrate the Iterator and Iterable interfaces, showing how
* to write a simple Iterator for an Array of Objects.
* @author Ian Darwin, http://www.darwinsys.com/
*/
public
public class
implements
Iterable
<
T
>,
Iterator
<
T
> {
/** The data to be iterated over. */
protected
class
ArrayIterator
ArrayIterator
<
T
>
implements
protected
T
[]
data
;
protected
protected
int
int
index
=
0
;
/** Construct an ArrayIterator object.
* @param d The array of objects to be iterated over.
*/
public
public
ArrayIterator
(
final
final
T
[]
d
) {
setData
(
d
);
}
/** (Re)set the data array to the given array, and reset the iterator.
* @param d The array of objects to be iterated over.
*/
public
public
void
void
setData
(
final
final
T
[]
d
) {
this
this
.
data
=
d
;
index
=
0
;
}
// -------------------
// Methods of Iterable
// -------------------
@Override
public
public
Iterator
<
T
>
iterator
() {
index
=
0
;