Are two Java objects with same hashcodes not necessarily equal?

后端 未结 9 2142
礼貌的吻别
礼貌的吻别 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:20

    As a matter of fact

    public int hashCode(){
        return 1;
    }
    

    Is a valid hashcode implementation...but a terrible one. Will make all your hashtables slow. But yes, you can have two different objects with the same hashcode. But that should not be the general case, a real implementation should give different hashcodes for different values most of the time.

提交回复
热议问题