我正在实施自己的LinkedList
。现在,我正在使用clear()
函数删除列表中的所有元素。
到目前为止,这是我的代码:
public class LinkedList<E> {
// the first element of this LinkedList
private Node start;
// the last element of this LinkedList
private Node end;
// the number of elements that constitute this LinkedList
private int length;
private class Node {
private Node last;
private Node next;
private E data;
// each Node has a reference to the previous Node and
// the next Node. The first element of the LinkedList
// will have a null reference to the previous element
// and the last element will have a null reference to
// the next element. Each Node stores a piece of data
// in the data variable.
}
public void clear() {
start = null;
end = null;
length = 0;
}
// other methods omitted
}
在clear()
函数中,我将start
和end
引用设置为null
。我不确定这将如何影响链表中间的节点(甚至是start
和end
节点)。
如果我LinkedList
中有四个节点(或更多),则中间两个(或更多)将指向彼此。将start
和end
设置为null
后,我的代码就不再引用这些对象,但它们互相引用。
这些中间节点,甚至是起点和终点节点是否有资格进行垃圾收集,为什么?
奖金问题:我怎么能通过实验来解决这个问题?
答案 0 :(得分:1)
在我看来,你担心这里的错误。 GC将跟踪所有根并为他们清除子项。对于您的示例,这意味着只要活动线程未使用LinkedList,它就有资格进行垃圾收集,即使子将指向某些实际数据(在您的情况下为节点)。即使将某个数据与某些数据联系起来,拥有一个不再需要的对象有什么用呢?
LinkedList
| |
Node1 Node2
如果LinkedList是Garbage Collected,那么节点也是如此,你不必担心这一点。因此,您的clear方法必须将LinkedList重置为默认值,并且不用担心GC。
P.S。您可能想要了解GC的工作原理,至少要了解其根源。
答案 1 :(得分:0)
不要显式地为对象设置null ...你在某个范围内创建链表对象,当范围结束时(连同节点)有资格被垃圾收集。
如果它的Web应用程序写了finalize()来记录消息。