I have a model class as follows:
package MyPackage.Models;
public class MyModel {
private int id;
public MyModel() {
}
public MyModel(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
From this class, I create two objects as follows and value them. I want that when I change the value of b, the value of a does not change. When I change the value of b, the value of a also changes.
MyModel a = new MyModel();
MyModel b = new MyModel();
a.setId(1);
Log.i("nadertag", "a=" + a.getId());
b = a;
Log.i("nadertag", "b=" + b.getId());
b.setId(2);
Log.i("nadertag", "a=" + a.getId() + "," + "b=" + b.getId());
It should be noted that this is a simple model class and the main program has many fields that I cannot place them one by one in the b variable.
Please show me the sample solution.
Just follow as below:
public class MyModel implements Cloneable{
private int id;
public MyModel() {
}
public MyModel(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
and wherever you want to get another object, simple perform cloning. e.g:
MyModel a = new MyModel();
MyModel b = (MyModel) a.clone();