The hashCode method in the Object class returns the hash code for the Object. This is an int value that is used as a key when objects are placed in a Hashtable.Objects that are equal must produce the same hashCode value; otherwise, they will not behave correctly in hash-based Collections. This means that if we override the equals method, as in Employee class, we must also override the Object hashCode method. We cannot rely on the default Object hashCode value. For example, for the following Employee objects e1 and e2:
Employee e1 = new Employee(1, ''Sim", 15000);
Employee e2 = new Employee(1, "Sim", 15000);
the values of e1.hashCode() and e2.hashCode() are derived from each instance's memory address and so will not be the same. The listing shows an overridden hashCode method that we might add to the Employee class.
hashCode
public int hashCode()
{
int result = 17;
result=37 * result +empNumber;
result=37 * result +name.hashcode();
result=37 * result +salary;
return result;
}
The derivation of the algorithm used in the preceding hashCode method is beyond the scope of this blog. It is sufficient to note that we have two main objectives when creating a hashCode method. First, equal objects must have the same hash code. Second, a hash method should distribute unequal instances uniformly across all possible hash values.2
hashCode Method in Java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment