10

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.

14
  • 1
    @WilliamF.Jameson Basically he wants a shorthand for the first 3 lines of code which are always the same (boilerplate code). Aug 7, 2014 at 13:39
  • 3
    @RogerWernersson Why don't you just write these helper methods (which would encapsulate the boilerplate code) yourself? I mean, if a method is not there, it's not there. Aug 7, 2014 at 13:41
  • 1
    @peter.petrov It is a legitimate (and indeed advisable) approach to ask if one is missing something which may already have been provided by the JDK. Aug 7, 2014 at 13:49
  • 1
    Does the removal of 3 lines of code warrant the addition of 2 method calls?
    – John B
    Aug 7, 2014 at 13:50
  • 2
    @NikolaKolev I for one never let that happen because it creates a whole screenful of boilerplate code. Signal-to-noise ratio plummets. Aug 7, 2014 at 13:58

4 Answers 4

4

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);
  }
}
5
  • Interesting. I have heard that the use of insanceof is very inefficient, so I'm reluctant use it. I like the use of values() which allows for really short methods, which we could implement in a common base class. Although i really should be part of Object to be really nice. I guess we could add rules to Sonar or similar that no class, except the new base class, may inherit directly from Object. Aug 10, 2014 at 10:19
  • instanceof won't incur significant costs in a modern JVM - whether to use instanceof or getClass() is a design decision you need to make depending on the inheritance strategy/class contract. More of a concern for the above approach are the heap allocation/garbage collection costs. Every invocation of values() causes the allocation of an array for the varargs and the instantiation of a List type to decorate it. The autoboxing of the long value may also cause a new Long to be created.
    – McDowell
    Aug 10, 2014 at 17:15
  • Also, if you plan to move to Java 8 there are things you can do with lambdas.
    – McDowell
    Aug 11, 2014 at 17:54
  • Won't I get a NullPointerException if obj is null? Jan 9, 2015 at 7:54
  • obj instanceof BrevityBeforeEfficiency guards against null. null is not an instance of any type.
    – McDowell
    Jan 9, 2015 at 10:04
2

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()
}
1
  • This has a completely different use case than what OP is asking about. It is quite recognizable from the question that OP is looking for a solution which performs equally well as the long equals form. Aug 7, 2014 at 13:50
2

mixing in a bit of inheritance:

public abstract class BusinessObject
{
    protected abstract Object[] getBusinessKeys();

    @Override
    public int hashCode()
    {
        return Objects.hash(getBusinessKeys());
    }

    @Override
    public boolean equals(Object obj)
    {
        if(obj == null) return false;

        if(obj == this) return true;

        if(obj.getClass() != getClass()) return false;

        BusinessObject other = (BusinessObject) obj;

        return Arrays.deepEquals(this.getBusinessKeys(), other.getBusinessKeys());
    }
}

so the only boilerplate code is to extend BusinessObject and the single-lined getBusinessKeys():

public class Node extends BusinessObject
{
    private final String code;
    private final String name;

    public Node(String code, String name)
    {
        this.code = code;
        this.name = name;
    }

    @Override
    protected Object[] getBusinessKeys()
    {
        return new Object[] { code, name };
    }
}

It's the simplest and cleanest that I can think :)

0

Here could be an implementation:

public abstract class EqualsHelper<T> {

    @SuppressWarnings("unchecked")
    public static <U> boolean equals(U that, Object other, EqualsHelper<U> equalsHelper) {
        return that == other || other != null && that.getClass().equals(other.getClass()) && equalsHelper.equals(that, (U) other);
    }

    public abstract boolean equals(T that, T other);

}

Then:

@Override
public boolean equals(Object obj) {
    return EqualsHelper.equals(this, obj, new EqualsHelper<MyClass>() {

        @Override
        public boolean equals(MyClass that, MyClass other) {
            return Objects.equal(that.myFirstField, other.myFirstField)
                && Objects.equal(that.mySecondField, other.mySecondField);
        }

    });
}

I wonder if this can be considered as an anti-pattern, so don't hesitate to blame me if you think it actually is ;)

1
  • 1
    I like your fresh take on this, although it looks like even more boiler plate code. Aug 10, 2014 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.