I have an object that I added to a few different ArrayLists. I wanna avoid changing every list, so I'm trying to change the pointer so all the lists change. But I can't get that to work if I want to set the object to null. For example:
ArrayList<Point> list1 = new ArrayList<Point>();
ArrayList<Point> list2 = new ArrayList<Point>();
Point a = new Point(2, 3);
list1.add(a); list2.add(a);
At this point, both lists have an item pointing at the same object. With the value "2, 3". If I change the value of the object. Then both lists changes:
a.set(5,5);
Now both lists have an item of value "5, 5". But if I try to set the value to null.
a = null;
Now the a is set to null, but the object both lists is still "5, 5" and not null like I wanted. I even tried to add a method to the Point class to set itself to null. But I couldn't get that to work either. What could I do to delete the object on all lists by changing only the pointer?
You can change the state of an object held by a reference variable and this will be reflected in all variables that refer to the same object, but if you change the assignment of a reference variable, it effects only that variable. The object referred to is unchanged -- as would be expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With