java中的链表删除

时间:2015-07-03 11:18:59

标签: java linked-list

如何在java中完全删除链接列表。一些教程建议我应该逐节点删除它。但是,如果我简单地说出来,那会是错的吗?因为所有元素都有资格进行垃圾收集。

3 个答案:

答案 0 :(得分:2)

你做不到。您只能通过删除所有引用来推荐列表作为垃圾收集的候选者。

如果您拥有唯一的引用,则将该引用设置为null将安排对象进行垃圾回收。您可以使用System.gc() 建议垃圾收集,但这不是特别好的样式,并非所有JVM都支持它。

逐节点删除元素(使用clear()可以帮助一点,因为它会减少每个列表项上的引用数量。这将减少列表消耗的内存量。

答案 1 :(得分:0)

您可以将LinkedList引用变量指向null

任何引用null的引用变量都自动符合垃圾收集

的条件
List list = new LinkedList();
list.add("hi");
list = null; // now eligible for *Garbage Collection*, leave it for JVM to handle

此外,如果您执行list.clear(),则会清除此list内的所有元素,但不会清除list本身内的所有元素。

我们也可以调用System.gc(),但System.gc()无法确保垃圾收集器运行肯定,它只能要求JVM运行GC,但完全依赖于JVM,所以我们应该将其归功于JVM只能处理GC。

有关详细信息,请参阅此Oracle Doc here

答案 2 :(得分:0)

是的,您可以简单地将head指定为null,但为了安全起见(如果某些节点是从其他地方引用的话),最好将所有节点{{1 }}

如果查看null中的代码,clear()方法也会这样做。

java.util.LinkedList

/** * Removes all of the elements from this list. * The list will be empty after this call returns. */ 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++; } 在你的案例中引用first

您也可以参考此comprehensive answer