gpt4 book ai didi

java - AbstractList::equals() 的 JDK 实现不会首先检查列表大小是否相等

转载 作者:太空狗 更新时间:2023-10-29 22:56:38 26 4
gpt4 key购买 nike

奇怪的是,AbstractList::equals() 的默认 JDK 6 实现 似乎没有首先检查两个列表是否具有相同的大小:

public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof List))
return false;
ListIterator<E> e1 = listIterator();
ListIterator e2 = ((List) o).listIterator();
while(e1.hasNext() && e2.hasNext()) {
E o1 = e1.next();
Object o2 = e2.next();
if (!(o1==null ? o2==null : o1.equals(o2)))
return false;
}
return !(e1.hasNext() || e2.hasNext());
}

如果两个列表都包含很多项目,或者需要时间比较的项目,它将在意识到一个列表比另一个短之前将它们全部比较;在我看来,这真的很低效,因为甚至可以在不进行比较的情况下实现平等。

特别是在很多情况下,列表的大小在大多数情况下会有所不同。此外,大多数 Java List 实现具有 O(1) size() 性能(即使是 LinkedList,它在缓存中保持其大小)。

这种默认实现有充分的理由吗?

最佳答案

The operation of the equals method is specified in some detail, and it requires the O(n) behavior. While this may be suboptimal for subclasses whose size method is O(1), for some subclasses the size method may itself be O(n) and the requested behavior would actually be a degradation. In any event the spec is clear and this change cannot be made.

Note that a subclass may override equals if desired, inserting a size comparison when appropriate.

Reference.

关于java - AbstractList::equals() 的 JDK 实现不会首先检查列表大小是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18958113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com