Sohail Bhutto
Sohail Bhutto

Reputation: 91

Update object from list of objects without affecting original reference of object

Scenario is, i have a list of objects like ArrayList<MyObject>. When i modify the member (item/Myobject) of the list, it make changes to original reference of selected object of list. How to handle this scenario so that original reference of object (MyObject) remains the same.

Upvotes: 3

Views: 3670

Answers (2)

davidxxx
davidxxx

Reputation: 131326

You may use the clone() method but it has some important limitations. So I don't advise to do it.
Another way would be to create a new instance of MyObject by copying the state from the original instance in the new created instance.

You could add a factory method in MyObject that takes a MyObject object as parameter :

public MyObject(String message){
     this.message = message;
}

public static MyObject copy(MyObject original){
     MyObject copy = new MyObject(original.getMessage());
     return copy;
}

And you could do something like that 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 the modification, the elements containing in a List of MyObject, I think that you should not expose the List to the class clients. If the client forgets to do the copy, your requirement is not respected.
So you could provide a custom get() method in the class that contains the List to return the copy of the MyObject that is requested. It would produce a more reliable defensive copy.

Upvotes: 2

Shivam
Shivam

Reputation: 720

You can use cloning to solve your problem, Just make clone of the and then change into the original object, So old object reference will be available in clone object.

Student18 s1=new Student18(101,"amit");  

Student18 s2=(Student18)s1.clone(); 

now you can make changes in s1 and your old object data will be in s2.

Upvotes: 0

Related Questions