Implementing Java’s equals method

Mon 16 June 2008

There’s a lot of incorrect information on the web and even in published books on how to implement Java’s equals method. Ivan Memruk in his blog post The equals/instanceof pitfall describes this issue nicely. There is however a small error in his post; what he calls the reflexive property is actually the symmetric property of the equals method.

Reflexive is: a=a, whereas symmetric is: if a=b then also b=a. It’s this property, among others, that should hold for Java’s equals method. By using instanceof in equals() the symmetric property doesn’t hold. Instead use the getClass method. A good template for Java’s equals method would be:

public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o == null || getClass() != o.getClass())
        return false;


   // your customized check for equality goes here
}

Another good article on implementing equals() is Manish Hatwalne’s Equals and Hash Code

Comments