12/17/2008

Override the equals method and the hashCode method

When you compare two objects of your original class with an equals method, it is better to override Object class’s equals method in your original class so that overridden equals method can return true if two objects are “semantically equal”.

The equals method in the Object class returns true if the two objects are “equal”.

Override example
public class Test {
    public static void main(String[] args) {
        Cat c1 = new Cat(1);
        Cat c2 = new Cat(1);
        System.out.println(c1.equals(c2));
    }
}
class Cat { 
    private final int c;
    Cat(int c) {
        this.t = c;
    }
    public int getCatValue() {
        return c;
    }
    public boolean equals(Object obj) {
        if ((obj instanceof Cat) &&
            (((Cat)obj).getCatValue() == c)) {
            return true;
        } else {
            return false;
        }
    }
}

Result
true
_______

Override the hashCode method
It is highly recommended that you override the hashCode method in your original class when you override the equals method.
A HashXxx class such as the HashMap class stores objects based on their hash code, which enables a quick search.

The hashcode method in the Object class returns a unique hash code value.

Therefore, when you override it in your original class, it should return the same hash code value if the two objects are “semantically equal”.

An example of simple and appropriate implementation in the Cat class is as follows:


public int hashCode() {
    return c;
}

Using your original class within the Collection framework may become dangerous unless you override the hashCode method.