Update an object from a list of objects without affecting the original object reference
There is a script, I have a list of objects like ArrayList<MyObject>
. When I change the item (item / Myobject) in the list box, it makes the change to the original link of the selected list object. How to handle this scenario so that the original reference object (MyObject) remains unchanged.
source to share
You can use the method clone()
, but it has some important limitations. Therefore, I do not recommend doing this.
Another way is to create a new instance MyObject
by copying the state from the original instance to the newly created instance.
You can add a factory method in MyObject
that takes an object MyObject
as a parameter:
public MyObject(String message){
this.message = message;
}
public static MyObject copy(MyObject original){
MyObject copy = new MyObject(original.getMessage());
return copy;
}
And you can do something like this to copy the instance:
List<User> myObjects = new ArrayList<>();
myObjects.add(new MyObject("hello msg"));
MyObject copyObject = MyObject.copy(myObjects.get(0));
Now, if you want to protect from modification, elements containing List
of MyObject
, I think, that you should not stand List
for the class of customers. If a client forgets to make a copy, your requirement is not met.
Thus, you can provide your own get()
method in the class that contains List
to return a copy of the requested one MyObject
. This will create a more secure defensive copy.
source to share
You can use cloning to solve your problem, Just make a clone and then go to the original object. This way the old object reference will be available in the clone object.
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
now you can make changes to s1 and your old object data will be in s2.
source to share