Question: I have questions about shallow copy and deep copy. Consider the following code:
Vector v = new Vector();
Vector v2 = v;
Is this the only way to make a shallow copy?
Answer:
Actually, you have not done a shallow copy at all. Rather, by creating v
and v2
,
you have created a second reference to the same object. A shallow copy
will make a complete copy of the object and any primitive
attribute. It will not, however, make copies of
any high-level object attributes. Instead, it points those attributes at
the
reference in the original object.
For a good introduction to how Java treats references, read: "Does Java pass by reference or pass by value? " (JavaWorld, May 26, 2000).