Daily tip #10
Tip of the day #10
Always override hashCode when you override equals. This is a good tip from Effective Java (read the book – 2 tips in 1 today)
Why?
If you don’t override hashCode, you will get the default implementation from Object, which is based on the memory address of the object.
From object definition:
-
This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.
-
This integer need not remain consistent from one execution of an application to another execution of the same application.
-
If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
-
It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Two important lessons from Effective Java:
-
“Do not be tempted to exclude significant fields from the hash code computation to improve performance.”
The final result can be exactly the contrary, because the hash code will be based on fewer fields, and programs that should run in linear time will run in quadratic time.
-
“Don’t provide a detailed specification for the value returned by hashCode, so clients can’t reasonably depend on it; this gives you the flexibility to change it.”
If you provide a detailed specification, you will be stuck with it forever, and you will not be able to change it without breaking the contract.
How to
Take a look in repo-tip-10 to see a real example of today’s tip.