Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

equals

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.

like image 629
John Topley Avatar asked Nov 16 '09 15:11

John Topley


1 Answers

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.

like image 157
Abel Avatar answered Oct 05 '22 05:10

Abel