Why does the Hashcode of an Object change in Java?

2019-02-26 10:57发布

问题:

Why does the Hashcode of an Object change in Java? Does it change at all? How is it related to Hashtable ? Every object should have it's unique hashcode.So, is Rehashing a reason for it ?

Thanks in advance.

回答1:

The default implementation of hashcode is equivalent to object identity. However, some objects override hashcode, which might give you a hashcode that changes based on object state.

Usually you do this if you're overriding the definition of equals( in fact, if you override equals you should override hashcode). This is because you want objects that are equal by whatever definition you've created to return the same hashcode. Otherwise you can have a situation a map holds multiple "equal" objects, because they return different hashcodes.



标签: java hash