What is the best way to override equals method in java to compare more than one field? For example, I have 4 objects in the class, o1, o2, o3, o4 and I want compare all of t
Use Guava:
@Override
public boolean equals(final Object obj){
if (!(obj instanceof Foo)) {
return false;
}
final Foo other = (Foo) obj;
return Objects.equal(o1, other.o1)
&& Objects.equal(o2, other.o2)
&& Objects.equal(o3, other.o3)
&& Objects.equal(o4, other.o4);
}
You get hashCode() for cheap, too:
@Override
public int hashCode() {
return Objects.hashCode(o1, o2, o3, o4);
}