Recipe for a high-quality “equals” method

By , last updated April 17, 2010

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.

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

Ref.”Effective Java” by Joshua Bloch

Enother example with hashCode and toString:

    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();

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

    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.


Be the first to comment.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>