Java Reference
In-Depth Information
Declaring the method
iterator
explicitly within the interface is permissible but not necessary,
because the interface extends
Iterable
. Since
Iterable
is in
java.lang
, no
import
statement is
needed for it.
As both
iterator
and
getIterator
have the same purpose, and since we have already imple-
mented
getIterator
, the implementation of
iterator
should call
getIterator
.
15.52
A class that implements the interface
Iterable
has a distinct advantage over classes that do not:
You can use a for-each loop to traverse the objects in an instance of such a class. For example, sup-
pose that we have
ListWithIteratorInterface
and
LinkedListWithIterator
, as described in the
previous segment. That is, the class
LinkedListWithIterator
implements
Iterable
. You can use
a for-each loop to display the items in an instance of this class.
Let's form a list, as follows:
ListWithIteratorInterface<String> nameList =
new
LinkedListWithIterator<String>();
nameList.add("Joe");
nameList.add("Jess");
nameList.add("Josh");
nameList.add("Jen");
The statements
for
(String name : nameList)
System.out.print(name + " ");
System.out.println();
then produce the following output:
Joe Jess Josh Jen
Programming Tip:
A class that defines an inner class iterator should implement the
interface
Iterable
. A client of the class then can use a for-each loop to traverse the objects in
an instance of the class.
15.53
The interface
java.util.List
that we described in Segment 12.12 of Chapter 12 extends the inter-
face
Iterable
, so it has the method
iterator
. Additionally,
List
declares the following methods
related to iterators:
public
ListIterator<T> listIterator(
int
index);
public
ListIterator<T> listIterator();
Each of the
listIterator
methods returns an iterator whose methods are specified in the interface
ListIterator
. The iterator returned by the first version of
listIterator
begins at the list entry
indicated by
index
, where zero indicates the first entry in the list. The second version of this
method has the same effect as
listIterator(0)
.
Since the classes
ArrayList
,
LinkedList
, and
Vector
of the package
java.util
implement
the interface
List
, they have these two
listIterator
methods as well as the method
iterator
.