• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

clone still pointing to original object

I cloned an object of my own class, but it still points to the same object.  I mean, when I make changes to the cloned object the original is changed as well.  How do I do this properly.  I implemented Cloneable and and overid clone().  So whats wrong.

public Object clone() {
        try {
            return super.clone();
        catch (CloneNotSupportedException e) {
            throw new InternalError(e.toString());


players = (Player[])playersInfo.clone();

  • 2
1 Solution
players = (Player[])playersInfo.clone(); -> this does not clone Player object but rather clone the array of players.
the cloned array will point to the same objects.
If you want to clone the whole array then you should do
Player[] newPlayers = new Player[playersInfo.length];
for (int i = 0; i < playersInfo.length; i++)
newPlayers[i] = (Player) playersInfo[i].clone();
The default/conventional behavior of clone() is to do a shallow copy. You can either override clone() to do a deep copy or provide a separate method to do a deep clone.

The simplest approach to deep cloning is to use Java serialization, where you serialize and deserialize the object and return the deserialized version. This will be a deep copy/clone, assuming everything in the tree is serializable. If everything is not serializable, you'll have to implement the deep cloning behavior yourself.

Assuming everything is serializable, the following should create a complete deep copy of the current class instance:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
Object deepCopy = ois.readObject();

Refer to



Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now