Thursday, January 19, 2012

equals()

Because the default hashCode() gives an answer based on the instance's identity, it is incorrect to implement equals() without implementing a corresponding hashCode() method. e.g.
public class Person {
    private String name;
    private Date birth;
    public boolean equals(Object other) {
        if (other == this) return true;
        if (other == null) return false;
        if (getClass() != other.getClass()) return false;
        Person person = (Person)other;
        return (
            (name == person.name ||
             (name != null && name.equals(person.name))) &&
            (birth == person.birth ||
             (birth != null && birth.equals(person.birth)))
            );
    }
}