Java Reference
In-Depth Information
and
team2
are created. Next, they are populated with some values. The
team3
object
is then set equal to the
team1
object, and the
team4
object is made a clone of the
team2
object. When the values are changed within the
team1
object, they are also
changed in the
team3
object because both object's contents refer to the same space in
memory. This is an example of a shallow copy of an object. When the values are
changed within the
team2
object, they remain unchanged in the
team4
object be-
cause each object has its own variables that refer to different spaces in memory. This is
an example of a deep copy.
In order to make an exact copy of an object (deep copy), you must serialize the ob-
ject. The base
Object
class implements the
clone()
method. By default, the
Ob-
ject
class's
clone()
method is
protected
. In order to make an object cloneable,
it must implement the
Cloneable
interface and override the default
clone()
meth-
od. You can make a deep copy of an object by serializing it through a series of steps,
such as writing the object to an output stream and then reading it back via an input
stream. The steps shown in the
clone()
method of the solution to this recipe do just
that. The object is written to a
ByteArrayOutputStream
and then read using a
ByteArrayInputStream
. Once that has occurred, the object has been serialized,
which creates the deep copy. The
clone()
method in the solution to this recipe has
been overridden so that it creates a deep copy.
Once these steps have been followed and an object implements
Cloneable
as
well as overrides the default object
clone()
method, it is possible to clone the object.
In order to make a deep copy of an object, simply call that object's overridden
clone()
method.
Team team4 = (Team) team2.clone();
Cloning objects is not very difficult, but a good understanding of the differences
that can vary with object copies is important.
5-11. Comparing Objects
Problem
Your application requires the capability to compare two or more objects to see whether
they are the same.