Delete this object inside the class

private class Node { Item name; Node next; public void deleteObject() { this = null; } } 

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

Edit: var1 and var2 refer to an object of this class, when I delete var1 by doing var1 = null , I want var2 also be deleted.

+4
source share
3 answers

No, It is Immpossible. Also not necessary.

An object will have the right to garbage collection (actually freed) as soon as it is inaccessible to one of the root objects. Basically, self-references do not matter.

Just make sure you never store references to objects that you will no longer use, and the rest will be handled by the garbage collector.

Regarding your editing:

Edit: var1 and var2 refer to an object of this class, when I delete var1 by doing var1 = null, I want var2 to be deleted too.

You cannot force another object to refuse the link. You must explicitly point this to another object. For example, if you are implementing a linked list (as it looks in your example), I would suggest you add the prev link 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). 
+9
source

No, you cannot delete this object or mark it for garbage collection in the same class.

And this not a variable, you cannot have keywords on the left side of the expression, therefore a compiler error.

0
source

Impossible. You must assemble the node as a "NodeManager", then you can remove Node from this "manager".

For example, if you create a Node List. You can remove the node from the list. Obviously, the List will contain the first node and a number of methods, and between them there is deleteNode.

See LinkedList

0
source

All Articles