Delete this object inside the class

巧了我就是萌 提交于 2020-01-13 11:43:08

问题


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.


回答1:


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



回答2:


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

And this is not a variable, you can not have keywords at leftside of expression so compiler error.




回答3:


Isn't possible. You should collect the node in a thing like "NodeManager" then from this "manager" you'll can delete the Node.

For example if you make a List of Node. You can delete the node from the list. Obviously, the List will contain the first node and a series of methods and between those there is deleteNode.

See LinkedList



来源:https://stackoverflow.com/questions/12089961/delete-this-object-inside-the-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!