Recipe for a high-quality “equals” method

By , last updated November 14, 2019

In this article we will show how to write a high quality Java equals override method with examples.

What is the difference between == and .equals() in Java?

The comparison sign “==” will check only if the two instances refer to the same object in memory.

You can use the “==” sign between primitives in Java. The comparison of the actual object contents won’t happen if you use the “==” sign.

Why do you need to implement an .equals() method?

If you need to compare the two objects in regards of their content. Two Person objects may not refer to the same instance in the computer memory, but they may still be the same person. You may need to compare the person’s name, age, address and some numbers in order to find out if it is the same person.

Rules for a high quality .equlas() method in Java

1. Use the == to check if the argument is a reference to this object.

2. Use the instanceof operator to check if the argument has the correct type.

3. Cast the argument to the correct type.

4. For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object.

5. Always override hashCode when you override equals.

6. Don’t substitute another type for Object in the equals declaration.

7. Write unit-test.

   @Override
   public boolean equals(Object obj) {
      if(obj == this) {
         return true;
      }
      if(!(obj instanceof Person)) {
          return false;
      }
      Person p = (Person)obj;
      return p.name.equals(name)
             p.birthday.equals(birthday)
             p.personNumber == personNumber;
      }

Ref.”Effective Java” by Joshua Bloch

Here’s a full example of a good overridden equals() method along with the hashCode() and toString() methods:

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !obj.getClass().isInstance(this)) {
            return false;
        }
        Beregning b = (Beregning) obj;

        return new EqualsBuilder()
                .append(simulertPensjon, b.getSimulertPensjon())
                .append(linjer.size(), b.getLinjer().size()).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().append(simulertPensjon).append(linjer).hashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
        .append("simulertPensjon", simulertPensjon)
        .append("antall linjer", linjer.size()).toString();
    }

Senior Software Engineer developing all kinds of stuff.