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?
Nothing. There’s no way you can do that. If you want to null the references to the object in the lists (or remove them from the lists) you must perform an operation on each of the lists.
If you cannot modify the lists, then consider the following alternatives:
Use a different
Pointclass that has an extra field that says if the point is “valid” and have the code that is looking at the lists check this field.Create a custom class that represents a nullable reference to a Point; e.g.
But both of these make using the lists and their contained Point objects more complicated.
(@Jeffrey’s answer suggests using the
WeakReferenceclass, but that has the wrong semantics. In particular, the reference will “break” if the GC detects that there are no strong references to the object. That’s NOT what your use-case requires … if I understand your question correctly.)Incidentally, I can’t think of ANY programming language that would allow you to do what you are trying to do in the way that you propose.