我担心这是一个非常愚蠢的问题,但这里是:
为什么 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++;
}
为什么要走路呢?为什么不直接跳到 header.next = header.previous = header;
?
据我所知,它是否有助于 GC...?此链接http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html#997442有点暗示。
TIA...
最佳答案
他们的方法确保即使其他代码仍然持有对特定节点的引用,其他节点也会被 GC。
否则,即使是对其中一个节点的单个外部引用也会阻止收集整个链。
此外,列表中的其他操作可能会同时进行(例如通过 subList()
或 Collections.unmodifiableList()
、迭代器进行查看),这确保了这些东西立即将列表视为“空”。
关于java - Java 的 LinkedList 中的 clear() impl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/575995/