Java Reference
In-Depth Information
PITFALL: (continued)
copy. You have what is known as a
shallow copy
. For example, assume that
Pet
is a
class with the usual kinds of accessor methods and consider the following code:
ArrayList<Pet> petList1 =
new
ArrayList<Pet>();
<Some code to set the instance variables of elements of
petList1
.>
ArrayList<Pet> petList2 = petList1;
petList2
and
petList1
are just two names for the same
ArrayList
object. Making
a change to
petList1
or to an element of
petList1
will also change
petList2
because they are the same list.
If you want an independent copy (deep copy) of
petList1
, you might think the
following would give you your independent copy:
ArrayList<Pet> petList2 = petList1.clone();
Unfortunately, the
clone
method also makes a shallow copy. There is no built-in
method to give you a deep copy (independent copy) of an
ArrayList
.
When you need a deep copy of an
ArrayList
, you will have to resort to some ad
hoc tricks. If you have a way to make a deep copy of objects of the base type, then you
can create a deep copy of each element in the
ArrayList
and place them into a new
ArrayList
object. This is the exact same approach as the one we discussed for mak-
ing a deep copy of an ordinary array in the subsection of Chapter 6 entitled “Privacy
Leaks with Array Instance Variables.” The situation with respect to deep copying of an
ArrayList
is exactly the same as the situation with respect to deep copying of an ordi-
nary array. Although the details of this subsection may seem subtle and diffi cult, they
are not new. You have already faced the exact same problem with ordinary arrays.
■
Self-Test Exercises
10. Can you have an
ArrayList
of
int
s ?
11. The following for-each loop was used in the method
showDifference
in
Display 14.3. Rewrite it as an ordinary
for
loop. This should help you to see
how much cleaner it is to use a for-each loop.
for
(Double element : a)
System.out.println(element + " differs from average by "
+ (element - average));
The
Vector
Class
The Java standard libraries have a class named
Vector
that behaves almost exactly
the same as the class
ArrayList
. In fact, everything we have said about the class
ArrayList
holds true for the
Vector
class. Although in almost all situations, you
could use either the class
ArrayList
or the class
Vector
, a clear preference seems to be
Vector