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.
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.
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.
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 =)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With