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 a utility method to help you
private static boolean nullSafeEquals(Object o1, Object o2) {
if(o1 == null && o2 == null) return true; // both null, both equal
if(o1 == null || o2 == null) return false; // if one is null, not equal - we know both won't be null
return o1.equals(o2);
}
public boolean equals(Object o) {
if(o instanceof ThisClass) {
ThisClass tc = (ThisClass)o;
return nullSafeEquals(o1, tc.o1)
&& nullSafeEquals(o2, tc.o2)
&& nullSafeEquals(o3, tc.o3)
&& nullSafeEquals(o4, tc.o4);
}
return false;
}