Null-safe comparision in Java

From Shrubbery

Jump to: navigation, search


Java Boiler Plate: Writing comparators that handle null pointers.

Contents


The boilerplate code

This code interprets null as being less than non-null and assumes that the two objects implement Comparable, which all the boxed primitives do. Thus, it's good for doing null safe comparison on Integer, Long, Double, String, etc.

package org.boilerplate;

public class ComparatorUtil
{
    public static int nullSafeCompare(Comparable a,Comparable b)
    {
        return a == null ?
                (b == null ? 0 : -1) :
                (b == null ? 1 : a.compareTo(b)
                );
    }
}

Using Jakarta Commons Collections NullComparator

This is much simpler and cleaner. You can pass your own comparator into NullComparator and set a boolean that tells the NullComparator whether null is higher than any value or lower than any value.

See Also