Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java help me avoid boilerplate code in equals()?

I implement equals() the Java 7 way:

@Override
public boolean equals(Object obj)
{
    if (this == obj) return true;
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    MyClass other = (MyClass) obj;
    return Objects.equal(myFirstField, other.myFirstField) &&
           Objects.equal(mySecondField, other.mySecondField);
}

Is there a way to reduce the code duplication?

I would prefer something like

@Override
public boolean equals(Object obj)
{
    if (Objects.equalsEarlyExit(this, obj)) return Objects.equalstEarlyExitResult(this, obj);
    MyClass other = (MyClass) obj;
    return Objects.equal(myFirstField, other.myFirstField) &&
           Objects.equal(mySecondField, other.mySecondField);
}

Or similar.

like image 853
Roger C S Wernersson Avatar asked Aug 07 '14 13:08

Roger C S Wernersson


2 Answers

Standard API Java with autoboxing and object creation inefficiencies:

import static java.util.Arrays.*;
import java.util.List;

class BrevityBeforeEfficiency {
  int foo;
  Object bar;
  boolean baz;

  @Override
  public boolean equals(Object obj) {
    return (obj instanceof BrevityBeforeEfficiency)
        && ((BrevityBeforeEfficiency) obj).values().equals(values());
  }

  @Override
  public int hashCode() {
    return values().hashCode();
  }

  private List<?> values() {
    return asList(foo, bar, baz);
  }
}
like image 130
McDowell Avatar answered Sep 20 '22 14:09

McDowell


You can use org.apache.commons.lang.builder.EqualsBuilder from commons-lang

Example:

public boolean equals(Object other) {
    return org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals(this, other);
}

Other example:

private boolean equalsHelper(Object obj) {
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
    return true;
}


public boolean equals(Object obj) {

    if (this == obj) return true;

    if(!equalsHelper(ob)) {
      return false;
    }

    MyClass other = (MyClass) obj;
    return new EqualsBuilder()
      .append(myFirstField, other.myFirstField)
      .append(mySecondField, other.mySecondField).isEquals()
}
like image 34
slavik Avatar answered Sep 19 '22 14:09

slavik