T
- The common type of the objects to be compared.public class NullSafeComparator<T extends Comparable<T>> extends Object implements Comparator<T>
This comparator performs Comparable.compareTo(Object)
if both objects
are non-null, and sorts null
to be -1 (before the non-null), and
compares two null
s as equal.
The static method compareObjects(Object, Object)
can be used if such
a comparison is needed without having to instantiate this class, for instance
because it is used within a Comparable.compareTo(Object)
or because
the two arguments are not of an agreeable subclass <Comparable
(but still can be compared).
Constructor and Description |
---|
NullSafeComparator() |
Modifier and Type | Method and Description |
---|---|
int |
compare(T a,
T b) |
static int |
compareObjects(Object a,
Object b)
Compare any two objects, null-safe.
|
static Integer |
nullCompare(Object a,
Object b)
Compare two objects for
null ity only. |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
comparing, comparing, comparingDouble, comparingInt, comparingLong, equals, naturalOrder, nullsFirst, nullsLast, reversed, reverseOrder, thenComparing, thenComparing, thenComparing, thenComparingDouble, thenComparingInt, thenComparingLong
public static Integer nullCompare(Object a, Object b)
null
ity only.
If both parameters are null
, return 0
. If only a
is null
, return -1
, if only b is
null
, return 1
. If none are null
,
return null
.
null
return might sound counter-intuitive, but it
basically means that the objects could not be compared on nullity alone,
and must be further compared.a
- First object to compareb
- Second object to comparenull
.public static int compareObjects(Object a, Object b)
If any of the parameters are null
, results are returned as
for nullCompare(Object, Object)
. Otherwise,
Comparable.compareTo(Object)
is called on the first parameter
against the second.
a
- First object to compare. Must be instance of
Comparable
.b
- Second object to compare. Must beClassCastException
- if the specified object's type prevents it from being
compared to this object.public int compare(T a, T b)
compare
in interface Comparator<T extends Comparable<T>>
Copyright © 2015–2016 The Apache Software Foundation. All rights reserved.