Java Reference
In-Depth Information
PITFALL:
(continued)
for the standard predefined collection classes, such as
ArrayList<T>
and
HashSet<T>
,
return references. So, you can modify the elements in the collection by using mutator
methods on
i.next( )
. This is illustrated in Display 16.17. The comments we made
about
i.next( )
also apply to
i.previous( )
.
The fact that
next
and
previous
return references to elements in the collection is
not necessarily bad news. It means you must be careful, but it also means you can cycle
through all the elements in the collection and perform some processing that might
modify the elements. For example, if the elements in the collection are records of some
sort, you can use mutator methods to update the records.
If you read the APIs for the
Iterator<T>
and
ListIterator<T>
interfaces, they say
that a
ListIterator<T>
can change the collection, but presumably, a plain old
Iterator<T>
cannot. These API comments do not refer to whether or not a reference
is returned by
i.next( )
. They simply refer to the fact that the
ListIterator<T>
interface has a set method, whereas the
Iterator<T>
interface does not have a set
method. Do not confuse this with the point discussed in the previous paragraph.
■
Display 16.17
An Iterator Returns a Reference
(part 1 of 2)
The class
Date
is defined in Display 4.13,
but you can easily guess all you need to
know about
Date
for this example.
1
import
java.util.ArrayList;
2
import
java.util.Iterator;
3
public
class
IteratorReferenceDemo
4{
5
public
static
void
main(String[] args)
6
{
7
ArrayList<Date> birthdays = new ArrayList<Date>( );
8
birthdays.add(
new
Date(1, 1, 1990));
9
birthdays.add(
new
Date(2, 2, 1990));
10
birthdays.add(
new
Date(3, 3, 1990));
11
System.out.println("The list contains:");
12
Iterator<Date> i = birthdays.iterator( );
13
while
(i.hasNext( ))
14
System.out.println(i.next( ));
15
i = birthdays.iterator( );
16
Date d = null;
//To keep the compiler happy.
17
System.out.println("Changing the references.");