You need to sort an object array that contains null
elements, and you want to have control over whether the null values are at the beginning or end of a
sorted array.
Wrap your Comparator in a
NullComparator from Commons Collections. The NullComparator can sort null values higher or lower than non-null values, depending on options passed into
the constructor. The following example shows a custom BookComparator wrapped with a NullComparator:
import org.apache.commons.collections.comparators.NullComparator;
import java.util.*;
Comparator bookComparator = new BookComparator( );
Comparator nullComparator = new NullComparator( BookComparator );
Book[] bookArray = new Book[] { new Book( ), null, new Book( ) };
Arrays.sort( bookArray, nullComparator );This example sorts an array of Book objects, placing null at the end of the sorted array; after the
sort, bookArray contains two Book objects at index zero and index one and a
null reference at index two.
To configure NullComparator to sort null values as less than non-null values, pass false to the constructor of NullComparator; to sort null values as greater than non-null values, pass true. By default, null values are sorted higher:
// null is less than non-null Comparator nullComparator = new NullComparator( bookComparator, false ); // null is greater than non-null (default) Comparator nullComparator = new NullComparator( bookComparator, true );
While the NullComparator
usually decorates another instance of Comparator, the NullComparator can also be used by itself to
compare null and non-null objects, as in the following
example:
Comparator nullHighComparator = new NullComparator( ); Comparator nullLowComparator = new NullComparator(false); // Returns 1 nullHighComparator.compare( null, new Double(3.0) ); // Returns -1 nullLowComparator.compare( null, new Double(3.0) ); // Returns 0 nullLowComparator.compare( null, null );
Both ReverseComparator and
NullComparator are objects that
decorate an existing Comparator. Take
note of the decorator pattern as it is a common pattern used throughout
Commons Collections. For more information about the decorator design
pattern, read Design Patterns: Elements of Reusable
Object-Oriented Software (Addison Wesley).
