John Topley John Topley - 2 years ago 76
Java Question

Most compact way to compare three objects for equality using Java?

What's the most compact code to compare three objects for (semantic) equality using Java? I have a business rule that the objects must be unique i.e. A is different to B, A is different to C and B is different to C.

Assume that the objects are all of the same class and have correctly overridden

methods. A slight wrinkle is that object C could be
—if this is the case then A and B have to be different to each other.

I have some code but it's a bit workmanlike for my tastes.

Answer Source

EDIT: I removed my first solution as it implemented the wrinkle-scenario as invalid, and it shouldn't

No need to check for null (shortest?):

if(A.equals(B) || B.equals(C) || A.equals(C))
   // not unique

and, as others have already suggested, you can put it in a method for reuse. Or a generic method if you need more reuse ;-)

EDIT: A note to first-timers (if any): the example uses a feature of equals: if its argument is null it should not throw, but return false.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download