I want to copy an object in java without copying reference.
Object o1 = new Object();
Object o2 = o1;
But o2 should not copy reference of o1. So any changes done in o2 must not affect o1.
How do we do this in java ?
I want to copy an object in java without copying reference.
Object o1 = new Object();
Object o2 = o1;
But o2 should not copy reference of o1. So any changes done in o2 must not affect o1.
How do we do this in java ?
You can override clone()
method which will create a copy of entire object graph (deep copy) and create a new object.
Note: Every class will inherit default clone()
implementation from Object class. But you must override the method to perform copy depending on the contents of your object.
Just FYI:
The default Object.clone() is a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable.
And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.
You can use Object.clone() method to clone the object:
Object o2 = o1.clone();
If you need copy other classes than Object, make a copy constructor or static factory method. Effect is something like this:
MyClass o1 = new MyClass();
MyClass o2 = new MyClass(o1); // in constructor make new object with data from o1 attributes
or
MyClass o1 = new MyClass();
MyClass o2 = MyClass.makeCopy(o1); // make static method for create new copy (similar like above)
Don't use clone. -> Effective Java