Why is a value class value like its hashCode “not a good idea”?

Last paragraph Paragraph 9 of Effective Java, 2nd Edn, J. Bloch says that for value classes such as Integer , String , Date , etc. returning the exact value function of this class as hashCode is not a good idea.

So, the Integer class that returns the value an integer, which it represents as the hashCode its instance, is not so good.

There is also no hashCode() String that returns an integer value that is directly displayed from the shared content, i.e. the characters that the String instance has.

These hashCode() -s are clearly contractual.

It seems to me that this is a good idea, not a bad one. hashCode -s change as values ​​change across objects, and these hashCodes “normalized” before they are distributed into buckets a HashMap / HashSet so that hashCode -s records do not form an offset over which the bucket will enter the record.

What I am missing here is what makes matching the class value directly with hashCode "bad idea"?

TIA

// =============================

EDIT

pls also see comments in response to Steve Sieber in connection with this.

+5
source share
3 answers

It is said that these javadoc specifications exactly determine how hashCode is created. By doing so, applications can now depend on this forever to be true ... and now these implementations can never change the way the hash code is generated.

This does not mean that you should not derive your hash from your values ​​... just do not tell people how you do it in your specification =)

+4
source

full quote

Many classes in the Java platform libraries, such as String , Integer and Date , include in their specifications the exact value returned by their hashCode method as a function of the instance value. This is generally not a good idea, as it greatly limits your ability to improve hash functions in future releases . If you leave the details of the hash function unspecified and a flaw is discovered or better, you can change the hash function in a subsequent release, I am sure that no client is dependent on the exact value returned by the hash function.

The emphasis is mine. The book simply says that it is generally considered bad practice to disclose implementation details in a specification. This makes it resistant to change.

The fact that it was implemented as returning an exact value (for Integer ) or some computed value (for Date and String ) is not bad.

+3
source

The Java API does just that, it returns an integer.

 Integer t = ...; t.intValue() == t.hashCode(); // true 

I have the same book at work. I will look at him on Monday.

If you are really worried, do the FNV-1a hash:

  int hash = 0x4C1DF00D; hash = (hash ^ value) * 0x01000193; 
-1
source

Source: https://habr.com/ru/post/1206498/


All Articles