this is my example object
object name: OBJ
object properties: String name, int age
now i have 2 global lists
List<OBJ> lstobj = new ArrayList<OBJ>;
List<OBJ> anotherlist = new ArrayList<OBJ>;
then i added a few records in both lists like this
Name:Ben Age:5
Name:Charles Age: 6
Name:Dan Age:7
Now I needed to change Charles’ age to “10”
and so first I should find Charles in the list and get the obj from the lists
OBJ newobj = new OBJ;
for(OBJ obj : lstobj){
if(obj.getName.equals("Charles"){
newobj = obj;
}
}
and now i need to set the retrieved obj’s age to 10.
newobj.setAge(10);
this action changes not just the “lstobj” but the “anotherlist” as well. How do i set the retrieved obj without affecting the two global lists?
Try using a copy constructor
The output is
In your case you are modifying just one object but reflects in both list.
This is because list stores object reference, here both the list refer to the same object that you are modifying so the changes that you make is reflected in both the list.
What i did here is that i am copying the objects details and creating a new object and its reference is different from the original object.
Any changes you make in the old object will not change the new one, since they have different references