Are two Java objects with same hashcodes not necessarily equal?

后端 未结 9 2139
礼貌的吻别
礼貌的吻别 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条回答
  •  -上瘾入骨i
    2020-11-27 07:15

    To prove , if two objects have the same hashCode does not mean that they are equal

    Say you have two user defined classes

        class Object1{
            private final int hashCode = 21;
            public int hashCode(){
                return hashCode;
            }
    
            public boolean equals(Object obj) {
                return (this == obj);
            }
        }
    
        class Object2{
            private final int hashCode = 21;
            public int hashCode(){
                return hashCode;
            }
    
            public boolean equals(Object obj) {
                return (this == obj);
            }
        }
    
        Object1 object1 = new Object1();
        Object2 object2 = new Object2(); 
    
        Object1 object3 = new Object1();
    
    
        if(object1.hashCode() == object2.hashCode()){
             // return true, because the hashcodes are same
        }
    
        but 
        if(object1.equals(object3)){
                // will fail, because two different objects   
        }
    

提交回复
热议问题