How to clone values of an object

Asked

Viewed 348 times

4

How can we make an object equal to the "values" of an object?

Whereas my object has other objects, and lists of other objects.

  • 2

    creates a Clone method that takes the Source object and the Target object and copies the values you need to the Target object

  • In case you have other objects inside you have to clone them as well. If they are lists you have to clone each of the elements of the list one by one.

1 answer

3


There are two options, basically (actually three, the third being "implement all yourself"):

  1. Implement the interface Cloneable

    Every Java object has a method clone, capable of making shallow copies of this object. This method is protected, so that it is normally not accessible. However, if you have the class implement Cloneable and override the method clone with the modifier public, then this method can be used to make such copies (in principle you don’t even need to implement anything, Java itself does the "magic" for you):

    public class MinhaClasse implements Cloneable {
        private int x;
        private String y;
        private float z;
    
        public Object clone() {
            return super.clone();
        }
    }
    

    The problem with this method is that, as I said, it makes copies shallow - If you have references to other objects, and lists of other objects, the clone will still reference the old objects. That is why it is necessary to implement logic in the method clone, which is not very convenient...

  2. Serialize your object and then deserialize it into another object

    A preferable option is to use one of the Java serialization tools to transform your object into an array of bytes (or a string) and then turn it back into an object. A simple medium (but not necessarily the most efficient) is through ObjectInputStream and ObjectOutputStream:

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

    This will make a deep copy, also copying each referenced object recursively, until the entire "object graph" has been copied (and what is better, keeping the references right, i.e. if A points to B and C, so much B how much C point to D, a single clone of D is created, referenced by the clones of B and C).

    For this to be possible, it is necessary for your class to implement Serializable, and only. At first, nothing else needs to be done on your part (except ensure that every referenced object also implement Serializable - but many of the objects built-in of Java already do so).

    Just take care not to serialize more than you want - if your object references others, which reference others, etc, it is very easy to suddenly have the entire memory of your program cloned at once... To avoid this, use the modifier transient in the fields that should not be serialized, and then they will be ignored (going back as null after the deserialization):

    public class MinhaClasse implements Serializable {
        private int x;
        private String y;
        private float z;
    
        private MinhaOutraClasse a; // Precisa também ser Serializable
        private OutraClasse[] b;    // idem
        private transient NaoCloneEsta c; // Não precisa ser, tanto faz
    }
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.