5

In Effective Java Item 9 (Always override hashCode when you override equals) where it says

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 severely limits your ability to improve the hash function in future releases.

What does it mean ?

2
  • What part don't you understand? Commented Dec 10, 2012 at 18:24
  • 1
    It means that the Java sources are not always a model of good programming style. Commented Dec 10, 2012 at 18:26

1 Answer 1

4

It means that you can't rewrite the hash function in later versions of your code to have better hashing properties. For example, the String.hashCode() function is fast...but not very good. But it can't be changed anymore, because the hash code was specified and people have depended on that implementation in their own code.

Sign up to request clarification or add additional context in comments.

4 Comments

What do you mean by, "because the hash code was specified and people have depended on that implementation in their own code"? Is it like someone does this: int hash = string.hashCode() And then later they do something stupid like assert(hash == 12345) ?
@Hiro2k - The API docs specify that String.hashCode() is computed by a specific formula. Client code is free to independently compute the hash code using that exact formula and assume it will be the same as that returned by String.hashCode(). This might seem perverse for pure Java code, but does make some sense with JNI. There are probably other cases where it would make sense to take advantage of the extra knowledge that the API specifies.
Can you explain a little bit why people think String.hashCode() is fast but not very good ? Does that mean the traditional way of calculating the hashcode by 31 is not good ?
There are a variety of important measures of hash functions that measure how good they are at spreading inputs evenly, such as the avalanche property, at which the java.lang.String implementation doesn't do very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.