Java的LinkedList中的clear()impl

ove*_*ink 11 java linked-list clear

我担心这是一个非常愚蠢的问题,但这里有:

为什么Java的默认LinkedList实现中的clear方法无法遍历列表并取消挂钩所有节点?为什么不解开标题并将列表的其余部分保持连接 - GC无论如何都会得到它,不是吗?

这是方法:

/**
 * Removes all of the elements from this list.
 */
public void clear() {
    Entry<E> e = header.next;
    while (e != header) {
        Entry<E> next = e.next;
        e.next = e.previous = null;
        e.element = null;
        e = next;
    }
    header.next = header.previous = header;
    size = 0;
modCount++;
}
Run Code Online (Sandbox Code Playgroud)

为什么走吧?为什么不跳过header.next = header.previous = header;

我能想到的最好的是它有助于GC ...?这个链接http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#997442有点暗示.

TIA ...

Jas*_*hen 18

他们的方法确保即使其他代码仍保留对特定节点的引用,其他节点也将被GC.

否则,即使对其中一个节点的单个外部引用也会阻止整个链被收集.

此外,列表中的其他操作可能同时进行(例如,通过subList()或通过Collections.unmodifiableList()迭代器查看),这可以确保那些事物立即将列表视为"空".