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.
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);
}
}
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With