0

Why would hashCode in java need not to be consistent during multiple execution? I want to understand if there is a reason in background!

From Object class JavaDoc:

This integer need not remain consistent from one execution of an application to another execution of the same application.

Mohammad Yasin
  • 130
  • 1
  • 8
  • 2
    Flip the question—why would it need to be? – Dave Newton Nov 22 '21 at 15:18
  • Thanks dave-newton. – Mohammad Yasin Nov 22 '21 at 15:24
  • Related: https://stackoverflow.com/questions/20339002/hashcode-value-changes-between-executions – Hulk Nov 22 '21 at 15:35
  • Another related question: https://stackoverflow.com/questions/2427631/how-is-hashcode-calculated-in-java – Hulk Nov 22 '21 at 15:45
  • The `hashCode` for an Integer is the `int` value that it wraps. If you ran the program say 20 times and each time added first 10, then 20, etc. to the `hashCode` would it not still hash those same values with the same frequency? So the frequency, not the values, of the generated `hashCodes` for the same values should be consistent between runs or your performance may vary. – WJS Nov 22 '21 at 15:53

1 Answers1

1

Object.hashCode()

This method is supported for the benefit of hash tables such as those provided by HashMap.

It is not required that it remains consistent across executions because that property is not needed to implement hash tables. It may be easier to implement it in a way that does not provide such guarantees. The contract for this method gives the implementation a lot of freedom to choose an efficient implementation, without imposing more restrictions than necessary.

Hulk
  • 6,399
  • 1
  • 30
  • 52