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

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.


Since I never start a Java project without using Apache commons-lang, try ObjectUtils.equals (it's null safe):

if (ObjectUtils.equals(a, b) || ObjectUtils.equals(b, c) || ObjectUtils.equals(a, c)) {
  // error condition
}

Put that logic in a generic method, and you'll do even better.

While the business logic allows C to be null, in scenarios like this, it's often better to code defensively and assume that either A or B could be null as well.

Tags:

Java

Equals