Skip to content
Advertisement

compareTo: treat two nulls as equal

I would like my compare method to work so that in the case where field1 == null in both objects, comparation would not be determined, but field2 would be checked, and so on. How to do it in the simplest way? The method below does not work well: when the fields from both objects are null, the comparison is always determined (without Ordering.natural().NullsFirst() I get NPE):

JavaScript

Advertisement

Answer

Having Ordering.natural().nullsFirst() as third parameter is the expected way.

The documentation shows it rather clearly:

JavaScript

Furthermore, ComparisonChain is in com.google.common.collect, which is annotated with @ParametersAreNonnullByDefault, and here are the complete definition of the two compare methods used for custom objects:

abstract ComparisonChain compare​(Comparable left, Comparable right)

And

abstract <T extends @Nullable Object> ComparisonChain compare​(T left, T right, Comparator comparator)

The first doesn’t have any parameter marked with @Nullable while the second, with the ordering does.

Therefore, there are no simpler way of doing what you do.

Advertisement