Consider the code below:
DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the dum
to dumtwo
and change dum
without affecting the dumtwo
. But the code above is not doing that. When I change something in dum
, the same change is happening in dumtwo
also.
I guess, when I say dumtwo = dum
, Java copies the reference only. So, is there any way to create a fresh copy of dum
and assign it to dumtwo
?
Here's a decent explanation of
clone()
if you end up needing it...Here: clone (Java method)
This works too. Assuming model
First add
compile 'com.google.code.gson:gson:2.8.1'
to your app>gradle & sync. ThenYou can exclude using a field by using
transient
keyword after access modifier.Note: This is bad practice. Also don't recommend to use
Cloneable
orJavaSerialization
It's slow and broken. Write copy constructor for best performance ref.Something like
Test stats of 90000 iteration:
Line
UserAccount clone = gson.fromJson(gson.toJson(aO), UserAccount.class);
takes 808msLine
UserAccount clone = new UserAccount(aO);
takes less than 1msConclusion: Use gson if your boss is crazy and you prefer speed. Use second copy constructor if you prefer quality.
You can also use copy constructor code generator plugin in Android Studio.
and in your code:
Create a copy constructor:
Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.
Other than explicitly copying, another approach is to make the object immutable (no
set
or other mutator methods). In this way the question never arises. Immutability becomes more difficult with larger objects, but that other side of that is that it pushes you in the direction of splitting into coherent small objects and composites.Add
Cloneable
and below code to your classUse this
clonedObject = (YourClass) yourClassObject.clone();