Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete this object inside the class

Tags:

java

class

private class Node
{
    Item name;
    Node next;

    public void deleteObject()
    {
        this = null;
    }
}

Is it possible to delete object inside class? I am trying to do above, but it gives an error, that left-side should be a variable. Node is inner class. Thank you.

Edit: var1 and var2 has reference to the object of this class, when I delete var1 by doing var1 = null, I want that var2 would be deleted too.

like image 763
good_evening Avatar asked Jan 15 '23 18:01

good_evening


1 Answers

No, that's not possible. Neither is it necessary.

The object will be eligible for garbage collection (effectively deallocated) as soon as it is not reachable from one of the root objects. Basically self-references doesn't matter.

Just make sure you never store references to objects which you won't use any more and the rest will be handled by the garbage collector.

Regarding your edit:

Edit: var1 and var2 has reference to the object of this class, when I delete var1 by doing var1 = null, I want that var2 would be deleted too.

You can't force another object to drop its reference. You have to explicitly tell that other object to do so. For instance, if you're implementing a linked list (as it looks like in your example), I would suggest you add a prev reference and do something like:

if (prev != null)
    prev.setNext(next);  // make prev discard its reference to me (this).

if (next != null)
    next.setPrev(prev);  // make next discard its reference to me (this).
like image 193
aioobe Avatar answered Jan 25 '23 23:01

aioobe