删除里面的类此对象(Delete this object inside the class)

2019-09-21 13:11发布

private class Node
{
    Item name;
    Node next;

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

是否有可能删除内部类对象? 我想上面的事,但它给出了一个错误,即左侧应该是一个变量。 Node是内部类。 谢谢。

编辑: var1var2具有参考这个类的对象,当我删除var1var1 = null ,我想这var2也会被删除。

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


Answer 2:

不,你不能删除this对象或将其标记为同一类垃圾回收。

this是不是一个变量,你不能表达莱夫特赛德所以编译器错误有一个关键字。



Answer 3:

是不可能的。 你应该收集节点,如“节点管理器”的事情,然后从这个“经理”你可以删除节点。

例如,如果你让节点的名单。 您可以从列表中删除的节点。 显然,列表将包含第一个节点和一系列的方法和那些之间有deleteNode。

见链表



文章来源: Delete this object inside the class
标签: java class