Are two Java objects with same hashcodes not necessarily equal?

后端 未结 9 2169
礼貌的吻别
礼貌的吻别 2020-11-27 06:34

I understand why providing same hashcode for two equal (through equals) objects is important. But is the vice versa true as well, if two objects have same hash

9条回答
  •  天命终不由人
    2020-11-27 07:18

    Curiously, NumberFormat is an example of a Java foundation class which violates the recommendation that:

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects.

    Here is some code showing this, at least under the version of Java I'm currently running under Mac OS X 10.6.

    Numberformat nf = NumberFormat.getNumberInstance();
    NumberFormat nf2 = NumberFormat.getNumberInstance();
    assert nf != nf2;  // passes -- they are different objects
    assert !nf.equals(nf2);  // passes -- they are not equal
    assert nf.hashCode() != nf2.hashCode();  // fails -- same hash code
    

提交回复
热议问题