Wednesday, December 12, 2012

hashCode() and equals()

Rule 1: The connection between hashCode() and equals():
If x.equals(y), then x.hashCode() must be same as y.hashCode().

Rule 2: Overwriting hashCode() or equals():
If you overwrite one of these functions, you have to overwrite the second too.

When you need to overwrite equals?

If you have  custom class which you will use as a key in HashMap/Hashtable (etc.) you have to overwrite equals. And according the Rule #2, you have to overwrite hashCode() too.

x.equals( null ) = ?
This have to be false. Check your code for it and for causing NullPointerException.

Implementing hashCode
When you have compound class, you have to use the hashCode of compound objects in it. Here is a good example:
public class Employee {
    int        employeeId;
    String     name;
    Department dept;

    // constructors, getters, setters...


    @Override

    public int hashCode() {
        int hash = 1;
        hash = hash * 13 + employeeId;
        hash = hash * 29 + name.hashCode();
        hash = hash * 17 + (dept == null ? 0 : dept.hashCode());
        return hash;
    }
}

Is this legal implementation of hashCode(): return 1;
Yeas, it is. All equal objects will be with equal hashes. But it is very bad implementation. All collections which use this hash, will suffer from extreme low performance, during internal collection collisions.

No comments:

Post a Comment