The contract of hashcode in java
- Inrrespective of the number of times hashcode is invoked on an object , it should return the same value.
- If two objects are equal then the hashcode values should also be the same.
Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.
So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values
So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be
public int hashCode(){
int result = 17;
result += 37 * field1;
result += 37 * field2;
return result;
}
Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.
No comments:
Post a Comment