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 equals
and hashCode
methods. A slight wrinkle is that object C could be null
—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.
As the OP said A
and B
are never null, C
may be null, use this:
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 ;-)
Note that in Java, a feature of equals
is that if its argument is null
it should not throw, but return false.
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