Java Reference
In-Depth Information
Display 16.17
An Iterator Returns a Reference
(part 2 of 2)
23 System.out.println("The list now contains:");
24 i = birthdays.iterator();
25
while
(i.hasNext())
26 System.out.println(i.next());
27 System.out.println("April fool!");
28 }
29 }
Sample Dialogue
The list contains:
January 1, 1990
February 2, 1990
March 3, 1990
Changing the references.
The list now contains:
April 1, 1990
April 1, 1990
April 1, 1990
April fool!
TIP: Defining Your Own Iterator Classes
There really is little need to define your own
Iterator<T>
or
ListIterator<T>
classes. The most common and easiest way to define a collection class is to make
it a derived class of one of the library collection classes, such as
ArrayList<T>
or
HashSet<T>
. When you do this, you automatically get the method
iterator()
, and
if need be, the method
listIterator()
, which takes care of iterators. However, if you
should need to define a collection class in some other way, then the best way to define
your iterator class or classes is to define them as inner classes of your collection class.
■
Self-Test Exercises
9. Does a
HashSet<T>
object have a method to produce a
ListIterator<T>
?
Does an
ArrayList<T>
object have a method to produce a
ListIterator<T>
?
10. Suppose
i
is a
ListIterator<T>
. Will an invocation
of i.next()
followed
by
i.previous()
return the same element for each of the two invocations or
might they return two different elements? What about
i.previous()
followed
by
i.next()
?