How do you properly override the equals() method? For example, what considerations should be taken when checking for equality?

tag: java-faq

Copied from Link

class Complex {

    private double re, im;

    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }

    // Overriding equals() to compare two Complex objects
    @Override
    public boolean equals(Object o) {

        // If the object is compared with itself then return true  
        if (o == this) {
            return true;
        }

        /* Check if o is an instance of Complex or not
          "null instanceof [type]" also returns false */
        if (!(o instanceof Complex)) {
            return false;
        }

        // typecast o to Complex so that we can compare data members 
        Complex c = (Complex) o;

        // Compare the data members and return accordingly 
        return Double.compare(re, c.re) == 0
                && Double.compare(im, c.im) == 0;
    }
}

As a side note, when we override equals(), it is recommended to also override the hashCode() method. If we don’t do so, equal objects may get different hash-values; and hash based collections, including HashMap, HashSet, and Hashtable do not work properly (see this for more details). We will be coverig more about hashCode() in a separate post.

References: Effective Java Second Edition