iteye_3420 2011-09-08 17:16
浏览 672
已采纳

关于LinkedList中的clear方法实现的疑问

clear方法的源码如下,在代码里他循环了所有item,将其previous和next全部设置成了null,目的何在?
[code="java"]
public void clear() {
Entry e = header.next;
while (e != header) {
Entry next = e.next;
e.next = e.previous = null;
e.element = null;
e = next;
}
header.next = header.previous = header;
size = 0;
modCount++;
}
[/code]
如果改成如下实现会有什么影响呢?其他的item都已经访问不到了,应该也不会影响GC啊。
public void clear() {

    header.next = header.previous = header;
    size = 0;
modCount++;
}

[/code]

  • 写回答

30条回答 默认 最新

  • jkxydp 2011-09-21 08:50
    关注

    看了楼主的图之后我觉得自己之前搞错了,先向楼主和看客道个歉。
    但是这也并非楼主说的加快GC回收那么简单。
    为了这个我便仔细地去读了一下LinkedList的源代码,原来发现惑起Iterator。
    [code="java"]
    private class ListItr implements ListIterator {
    private Entry lastReturned = header;
    private Entry next;
    private int nextIndex;
    private int expectedModCount = modCount;

    ListItr(int index) {
        if (index < 0 || index > size)
        throw new IndexOutOfBoundsException("Index: "+index+
                            ", Size: "+size);
        if (index < (size >> 1)) {
        next = header.next;
        for (nextIndex=0; nextIndex<index; nextIndex++)
            next = next.next;
        } else {
        next = header;
        for (nextIndex=size; nextIndex>index; nextIndex--)
            next = next.previous;
        }
    }
    
    public boolean hasNext() {
        return nextIndex != size;
    }
    
    public E next() {
        checkForComodification();
        if (nextIndex == size)
        throw new NoSuchElementException();
    
        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.element;
    }
    

    ......
    }
    [/code]
    如源代码所示,如果程序员对该List对象使用过iterator,并且迭代到中间就断了,那么栈内就会有一个引用指向Iterator对象,而Iterator对象中又有lastReturned 引用指向一个Entry再结合上图就不难理解整条链得不到释放,GC不能回收的疑惑了。

    郑重地向楼主道歉,之前我真向简单了点。
    不过该观点估计也不一定对,有鉴于之前的幼稚的想法。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料