Alex Rivera | Logout

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

Asked 2009-11-16T15:46:41.027
9

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.

Edit
Report

1 Answer

6

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.

answered 2009-11-16T15:54:05.210

Your Answer