什么是比较符合equals是什么意思?如果我的班级不遵循这个原则,可能会发生什么? [英] What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?

查看:472
本文介绍了什么是比较符合equals是什么意思?如果我的班级不遵循这个原则,可能会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从TreeMap的JavaDoc中:

From the JavaDoc of TreeMap :


请注意,排序维护的排序(无论
是否显式比较器)必须与equals一致,如果
这个排序映射是为了正确实现Map接口。 (请参阅
Comparable或Comparator,以获得与
equals一致的精确定义)。这是因为Map接口是以
的equals操作定义的,但是一个映射执行所有关键字比较使用其
compareTo(或compare)方法,因此从排序映射的角度来看,被认为等于
的两个键是相等的。排序映射的
行为是明确定义的,即使其排序是
与equals不一致;它只是没有遵守Map接口的一般合同

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

有人可以给出一个具体的例子来说明如果排序与equals不一致,可能会出现问题?例如,用户定义的类具有自然排序,即实现Comparable。还要做所有内部类在JDK维护这个不变的?

Can some one give an concrete example to demonsrate the problem that might occur if ordering is not consistent with equals ? Take for example User defined class that has a natural ordering i.e it implements Comparable . Also do all internal classes in JDK maintain this invariant?

推荐答案

Comparable接口的合同允许不一致的行为:


强烈建议(虽然不是必须的)自然顺序与等号一致。

It is strongly recommended (though not required) that natural orderings be consistent with equals.

所以在理论上,JDK中的一个类a compareTo equals 不一致。一个很好的例子是 BigDecimal

So in theory, it is possible that a class in the JDK had a compareTo not consistent with equals. One good example is BigDecimal.

下面是一个比较器的例子,它与equals不一致(它基本上说所有字符串都相等)。

Below is a contrived example of a comparator that is not consistent with equals (it basically says that all strings are equal).

输出:


大小:1

content:{a = b} p>

size: 1
content: {a=b}



public static void main(String[] args) {
    Map<String, String> brokenMap = new TreeMap<String, String> (new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return 0;
        }
    });

    brokenMap.put("a", "a");
    brokenMap.put("b", "b");
    System.out.println("size: " + brokenMap.size());
    System.out.println("content: " + brokenMap);
}

这篇关于什么是比较符合equals是什么意思?如果我的班级不遵循这个原则,可能会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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