Search code examples
javaobjectclone

assigning same values to objects in java


let's suppose there are two objects of class abc

abc obj = new abc(10,20); // setting the values of two var. say x and y

abc obj1 = obj; // pointing to same memory so same values

But if there is a way where I can assign the values of one object to another, both having diff. memory. Simply said I want the values to copied not the address. Any operator or something can do that ?


Solution

  • You can use the clone() method (assuming the subclass implements the java.lang.Cloneable interface)

    abc obj1 = obj.clone()
    

    Bear in mind the default behavior of clone() is to return a shallow copy of the object. This means that the values of all of the original object’s fields are copied to the fields of the new object(it will not go through the entire graph of other objects).

    I you want to "deep-copy" the object you can serialize and deserialize it.

    A deep copy makes a distinct copy of each of the object’s fields, recursing through the entire graph of other objects referenced by the object being copied

    more info at:

    http://javatechniques.com/blog/faster-deep-copies-of-java-objects/