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
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)
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
There are a few ways to approach this.
You can roll your own - that has the highest likelihood of getting something subtle wrong.
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.
You can use EqualsBuilder; it avoids the aforementioned problems.
Best of all, at least in my experience, you can use lombok's EqualsAndHashCode annotation.
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;
}