3

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.

asked Aug 15, 2011 at 15:50
2

1 Answer 1

5

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.

answered Aug 15, 2011 at 15:53
2
  • 3
    Or worse, the object's hashcode changes while it's in the map and you lose that outside reference. The only way to get it back would be to iterate over the map and do an equals on your criteria. Commented Aug 15, 2011 at 15:56
  • 1
    That is a really, really unpleasant thought - I'd never worried about that particular possibility, but now I will. Excellent name, btw. Commented Aug 15, 2011 at 16:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.