Java Reference
In-Depth Information
PITFALL:
(continued)
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 making
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 difficult, 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
showDiffernce
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 developing
among programmers for the class
ArrayList
. There are some differences between
the classes
Vector
and
ArrayList
, but the differences involve material we have not
covered. If you encounter the class
Vector
in somebody's code, chances are the class
Vector
could be replaced by the class
ArrayList
and that would require at most cos-
metic changes in the code.
1
Vector
1
The biggest difference between the
Vector
and
ArrayList
classes is that
Vector
s are
synchronized
whereas
ArrayLists
are not. However, synchronization is a topic that we do not cover and is not rel-
evant to the kinds of programming we are doing.