Please consider the following code:
ArrayClass<someClass> list = new ArrayList<someClass>();
//Consider this list has been filled somewhere else
someClass selectedObject = null;
public void userAction(float x, float y){
selectedObject = findObject(x, y);
}
public someClass findObject(float x, float y){
for(int i=0; i<list.size(); i++)
if( --objects match-- )
return list.get(i);
return null;
}
The problem is that I'm using that selectedObject somewhere else, and I need to know that the object to which it points still exists. I've noticed that when the object in the list to which selectObject points is removed, the selectedObjects keeps the properties from the object it used to point to (which doesn't exist any more). I need selectedObject to point to null once the object is removed from the list. How can I achieve this?
EDIT1: To clarify, the posted code works, that is not the issue. The problem is that the pointer selectedObject is not updated when the object it points to in the list, is deleted. One more thing, I do not have access to the method that deletes objects from the list.
you can achieve this if you make selectedObject a weak reference:
WeakReference<someClass> selectedObject = null;
assignment:
selectedObject = new WeakReference<someClass>(findObject(x, y));
query:
someClass v = selectedObject.get();
selectedObject get() method will return null if the item is removed from the list (and is not referenced by any other "pointer")
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