只要使head = null删除单个链表? [英] Deleting a single linked list by just making head = null?

查看:216
本文介绍了只要使head = null删除单个链表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使 head = null 删除完整的链接列表?

Why can't I just make head=null to delete the complete Linked list?

3 = head > 1 > 2 > 4 > null

通过使 head = null ,JVM将会照顾它。由于头节点不被任何变量引用,所以应该是垃圾回收。

By making head = null, JVM will take care of it.As head node is not referenced by any variable , it should be garbage collected.

这个解决方案有什么问题?

What is wrong with this solution?

注意:我知道删除完整链接列表的正确解决方案,但我很好奇为什么我不能只是使 head = null 删除完整的链表?

Note: I'm aware of the correct solution to delete the complete link list but I'm curious why I can't just make head=null to delete the complete linked list?

推荐答案

这里是java.util.LinkedList.clear()的代码,逐字:

Here's the code of java.util.LinkedList.clear(), verbatim:

public void clear() {
    // Clearing all of the links between nodes is "unnecessary", but:
    // - helps a generational GC if the discarded nodes inhabit
    //   more than one generation
    // - is sure to free memory even if there is a reachable Iterator
    for (Node<E> x = first; x != null; ) {
        Node<E> next = x.next;
        x.item = null;
        x.next = null;
        x.prev = null;
        x = next;
    }
    first = last = null;
    size = 0;
    modCount++;
}

评论回答您的问题。没有必要但是,如果存在引用其中一个节点的迭代器,引用的节点仍然不符合GC,但是引用节点之前和之后的所有节点都可以帮助GC,并且可以使更多的对象有资格使用GC节点将被,因为它们不被引用。

The comment answers your question. It's unnecessary. But it can help the GC, and it can make more objects eligible to GC sooner if there is an Iterator that references one of the nodes: the referenced node still won't be eligible to GC, but all the nodes after and before the referenced node will be, since they're not referenced anymore.

请注意,开发人员选择使clear()方法更慢(O(n)而不是O(1) )),使GC更快,减少内存泄漏。你可以做相反的选择。

Note that the developer chose to make the clear() method slower (O(n) instead of O(1)), to make the GC faster and reduce "memory leaks". You could do the inverse choice.

还要注意,你可能永远不会调用clear(),并且只是停止引用LinkedList类型的对象,将所有节点链接在一起。 GC将收集所有节点,如果它们都不能通过GC根的参考链可达。这就是你使用列表的99%的时间。

Also note that you might never call clear(), and just stop referencing an object of type LinkedList, leaving all the nodes linked together. The GC will collect all the nodes if none of them is reachable through a reference chain from a GC root. That's what happens 99% of the times you use a list.

这篇关于只要使head = null删除单个链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆