Java Reference
In-Depth Information
The
ListIterator
interface that you saw in the preceding section is a
subinterface of
Iterator
with additional methods (such as
add
and
previous
).
The compiler translates a Ȓfor eachȓ loop into an equivalent loop that uses an
iterator. The loop
for (Type variable : collection)
body
is equivalent to
Iterator<Type> iter = collection.iterator();
while (iter.hasNext())
{
Type variable = iter.next();
body
}
The
ArrayList
and
LinkedList
classes implement the
Iterable
interface.
If your own classes implement the
Iterable
interface, you can use them with
the Ȓfor eachȓ loop as wellȌsee Exercise P15.15.
15.2 Implementing Linked Lists
In the last section you saw how to use the linked list class supplied by the Java
library. In this section, we will look at the implementation of a simplified version of
this class. This shows you how the list operations manipulate the links as the list is
modified.
To keep this sample code simple, we will not implement all methods of the linked list
class. We will implement only a singly linked list, and the list class will supply direct
access only to the first list element, not the last one. Our list will not use a type
parameter. We will simply store raw
Object
values and insert casts w
hen retrieving
them. The result will be a fully functional list class that shows how the
links are
updated in the
add
and
remove
operations and how the iterator traverses the list.
671
672
A
Node
object stores an object and a reference to the next node. Because the methods
of both the linked list class and the iterator class have frequent access to the
Node
instance variables, we do not make the instance variables private. Instead, we make