Why does the Hashcode of an Object change in Java?

2019-02-26 10:22发布

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.

标签: java hash
1条回答
Bombasti
2楼-- · 2019-02-26 10:58

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.

查看更多
登录 后发表回答