difference between equals() and hashCode()

前端 未结 7 606
心在旅途
心在旅途 2021-02-05 13:29

I want a brief definition about the equals() , \"==\" and hashCode(). If i run following code means the output will be \"true false 2420395 2420395\". But i had understand that

7条回答
  •  名媛妹妹
    2021-02-05 14:25

    You can read the hashCode documentation. In a few words it says that if (obj1.equals(obj2) is true then obj1.hashCode()==obj2.hasCode() must be true to be a valid implementation.

    Note that it does not mean that two different objects cannot share the same hash code. Actually, this example is a valid (but awful) implementation of the method:

    class MyClass {
        public int hashCode() {return 0;}
    }
    

提交回复
热议问题