Vallabh Patade
Vallabh Patade

Reputation: 5110

EqualsBuilder vs own equals method

I just came across a code using EqualsBuilder() in equals method. Is there any advantage of using it instead of writing (or generating from eclipse) our own logic? A simple example would be more helful.

Edit : If it doesn't have any benefits than having less code in the class, isn't there is overhead of reflection?

Upvotes: 5

Views: 3749

Answers (4)

Carl Manaster
Carl Manaster

Reputation: 40356

There are a few ways to approach this.

  1. You can roll your own - that has the highest likelihood of getting something subtle wrong.

  2. You can have Eclipse generate your equals and hashCode methods for you - that leaves a lot of code in place, subject to inadvertent edits, and subject to failure to update when the class acquires a new field.

  3. You can use EqualsBuilder; it avoids the aforementioned problems.

  4. Best of all, at least in my experience, you can use lombok's EqualsAndHashCode annotation.

Upvotes: 6

specializt
specializt

Reputation: 1911

Using ANYTHING except for your own implementation in equals() is GUARANTEED to be "worse" if you can use ... say a strictly unique ID.

If your ID is really unique you will most likely have the best, possible implementation with this, of course it needs to be polished quite a bit:

@Override
public boolean equals(Object other)
{
   if(other instanceof MyClass)
   {
      MyClass obj = (MyClass)other;
      return obj.getID() == this.getID();
   }
   else
      return false;
}

Have a look at this, this and especially this

Upvotes: -2

Michal Gruca
Michal Gruca

Reputation: 522

I don't see need for example. Equals builder will generate exactly same code for you so the only difference is that you have less code in a class.

From my perspective it's better to write those methods (as you always have to override hashCode when you override equals)

Upvotes: 0

sigpwned
sigpwned

Reputation: 7453

Using an EqualsBuilder is not implicitly better or worse than writing your equals method from scratch. In other words, I don't consider using EqualsBuilder to be a best practice.

A non-EqualsBuilder equals() method usually looks like this:

public boolean equals(Object other) {
    boolean result;

    if(this == other)
        result = true;
    else
    if(other == null)
        result = false;
    else
    if(other instanceof MyClass) {
        MyClass o=(MyClass) other;
        result = Objects.equals(this.a, o.a)
                 && Objects.equals(this.b, o.b)
                 // ...
                 && Objects.equals(this.z, o.z);
    }
    else
        result = false;

    return result;
}

Upvotes: 0

Related Questions