Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect object deletion through pointer

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.

like image 874
AmiguelS Avatar asked Jul 11 '26 19:07

AmiguelS


1 Answers

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")

like image 155
Sharon Ben Asher Avatar answered Jul 13 '26 11:07

Sharon Ben Asher