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
One thing is to have a helper method in a utility class:
public static boolean equals(Object o1, Object o2)
{
if (o1 == o2)
{
return true;
}
if (o1 == null || o2 == null)
{
return false;
}
return o1.equals(o2);
}
Then you can write:
public boolean equals(Object other)
{
if (other == null || this.getClass() != other.getClass())
{
return false;
}
Foo x = (Foo) other;
return Helper.equals(o1, x.o1) &&
Helper.equals(o2, x.o2) &&
Helper.equals(o3, x.o3) &&
Helper.equals(o4, x.o4);
}
Note that this way it also copes when two fields are both null, which the code in the question doesn't. (I say "copes" - it gives a result which is more consistent with the rest of Java.)
You can create a similar helper method for hashCode
too.
Note that Guava already supports this in its Objects class (and I'm sure many other utility libraries do too).