What is the hashCode method used for in Java?
HashCode's are used in hashing to decide which group (or bucket) an object should be placed into. A group of object's might share the same hashcode. The implementation of hash code decides effectiveness of Hashing. A good hashing function evenly distributes object's into different groups (or buckets).
A good hashCode method should have the following properties
? If obj1.equals(obj2) is true, then obj1.hashCode() should be equal to obj2.hashCode()
? obj.hashCode() should return the same value when run multiple times, if values of obj used in equals() have not changed.
? If obj1.equals(obj2) is false, it is NOT required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.
A sample hashcode implementation of Client class which meets above constraints is given below:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
No Comments Yet!!