JDK实现AbstractList :: equals()不会首先检查列表大小是否相等 [英] JDK implementation of AbstractList::equals() does not check for list size equality first

查看:228
本文介绍了JDK实现AbstractList :: equals()不会首先检查列表大小是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的是, 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());
}

如果两个列表都包含大量项目或项目需要时间进行比较将比较他们所有之前,意识到一个列表比另一个短;这似乎在我真的效率低下,因为平等本可以做,甚至没有调用一个比较。

If both lists contains lots of items, or items taking time to compare, it will compare them all before realizing that one list is shorter than the other; which seems to me really inefficient as the equality could have been made without even calling one compare.

特别是对于大多数情况列表,大多数情况下会有所不同。此外,大多数Java List 实现具有O(1) size()性能(即使LinkedList,缓存)。

Especially that for lots of situations lists sizes would most of the time differ. Furthermore, most Java List implementations have O(1) size() performance (even LinkedList, which keep its size in cache).

这个默认实现有很好的理由吗?

Is there a good reason for this default implementation?

推荐答案


equals方法的操作在一些细节中指定,它
需要O(n)行为。虽然这对于其大小方法为O(1)的
子类可能是次最佳的,但对于一些子类,大小
方法本身可以是O(n),并且所请求的行为实际上将是
a退化。在任何情况下规范是明确的,这种变化不能

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.

请注意,如果需要,子类可以覆盖equals,如果合适,插入大小
的比较。

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

参考

这篇关于JDK实现AbstractList :: equals()不会首先检查列表大小是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆