I know the contract says “if two objects are equal then they should return the same hash code”. That is so that those objects can be place in the same hash bucket and to improve hash code related collection functions know. Then again why it says “if two objects have same hash code those should not always be equals”. I mean if it is true in the contract we should say “if two objects are equals they may return same hash code but which is not mandatory”
Share
No, it should not. This is because, whenever an object is searched let’s say in a
HashMapor aHashSet, then first it is searched on the basis ofhashCode(NOTE : –hashCode()is not used for search in case ofArrayList, orLinkedList. They are nothash basedcollections), and then if the two objects have same hashcodes, it moves to theequalsmethod to compare the objects themselves.Now suppose if the above statement was true, the first test itself would fail for those objects. That is, if two equal objects are allowed to have different hashcode, then while searching for a particular hashCode, it won’t return the correct result, and thus the test will not proceed to
equals method, and declare those objects to beunequaleven though you expected them to be equal.Now lets move to the second statement: –
Let’s understand like this: – Since
hashCodegenerated for each object is of typeint, so you can generate a maximum2 ^ 32uniquehashcodes. So, imagine what would happen if you want to store more objects than that. In that case, there has to be a collison fortwo different objects. So, you would have no other way than to assign samehashCodesto two different objects. And hence the above statement is justified.So, two things are quite clear from the above explanation: –
More details on this topic in the below link (Nothing can give better explanation than this): –