Delete this object inside the class

2019-05-06 14:34发布

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.

标签: java class
3条回答
【Aperson】
2楼-- · 2019-05-06 15:13

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楼-- · 2019-05-06 15:26

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).
查看更多
男人必须洒脱
4楼-- · 2019-05-06 15:27

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

查看更多
登录 后发表回答