Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is value of a value class as its hashCode "not a good idea"?

The very last paragraph of Item 9 of Effective Java, 2nd Edn, J. Bloch says that, for value classes like Integer, String, Date etc, returning a function of the the exact value of that class as the hashCode isn't a good idea.

So, the class Integer returning the value of the integer it represents as the hashCode of its instance isn't all so good.

Neither is the hashCode() of String returning an integer value directly mapped from the overall content, i.e., the characters that the String instance has.

These hashCode()-s clearly comply with the contract.

To me, it seems to be a good idea rather than a bad one-- the hashCode-s vary as the values vary across objects, and these hashCodes are "normalized" before they are spread out into the buckets of a HashMap/HashSet-- so that the hashCode-s of the entries do not form a bias on which bucket the entry will go in.

What am i missing here - what makes mapping the class value directly to hashCode a "bad idea"?

TIA

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

EDIT

pls also see comments under Steve Siebert's answer in relation to this.

like image 312
Roam Avatar asked Nov 08 '14 20:11

Roam


People also ask

What happens if hashCode returns same value?

If multiple objects return the same value from hashCode(), it means that they would be stored in the same bucket. If many objects are stored in the same bucket it means that on average it requires more comparison operations to look up a given object.

Can different objects have same hashCode?

1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.


1 Answers

What it's saying is that those javadoc specification say exactly how the hashCode is created. By doing so, applications can now depend on this always to be true...and now those implementations can never change the way that the hashCode is generated.

It doesn't mean that you shouldn't derive your hash from your values...just don't tell people how you do this in your specification =)

like image 61
Steve Siebert Avatar answered Oct 19 '22 12:10

Steve Siebert