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.

Vipin Pillai
  • 155
  • 1
  • 8
  • Do you have an example of how it changes? – Marcelo Aug 15 '11 at 15:52
  • Maybe you should read this : http://stackoverflow.com/questions/6051960/how-to-write-a-good-hashcode-for-permutations and this : http://stackoverflow.com/questions/1990734/hashcode-and-equals – panzerschreck Aug 15 '11 at 16:08

1 Answers1

3

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.

Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • 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. – corsiKa Aug 15 '11 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. – Steve B. Aug 15 '11 at 16:00