真的很想知道为什么链表indexof()没有利用“标头”条目具有null元素来提高性能的事实,因为它传递了null“ target”:

public int indexOf(Object o) {
    int index = 0;
    if (o==null) {
        // header.element guaranteed null, no chance of looping past header
        for (Entry e = header.next; e.element != null; e = e.next) {
            index++;
        }
        // if index < size, null was found, else we looped to header
        return (index < size) ? index: -1;
    } else {
        for (Entry e = header.next; e != header; e = e.next) {
            if (o.equals(e.element))
                return index;
            index++;
        }
    }
    return -1;
}


如果我们对lastIndexOf()应用类似的转换,则会产生非常漂亮的结果:

public int lastIndexOf(Object o) {
    int index = size - 1;
    if (o==null) {
        for (Entry e = header.previous; e.element != null;
             e = e.previous, index--);
    } else {
        for (Entry e = header.previous; e != header && !o.equals(e.element);
             e = e.previous, index--);
    }
    return index;
}


是故意的吗?

最佳答案

我不确定您指的是JRE,但是除了语法糖以外,我看到的唯一相关区别是:

// if index < size, null was found, else we looped to header
return (index < size) ? index: -1;


这样做的原因是,对于lastIndexOf(),我们从最后一个元素开始,并且在未命中时,我们在索引为-1的标头处结束。但是对于indexOf(),我们从第0个元素开始,并且在未命中时以index == size结尾于标头-但是,我们要在未命中时返回-1,因此我们必须添加额外条件。

关于java - LinkedList的indexOf()vs lastIndexOf()方法优化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42548633/

10-11 13:39