In Java, I use a class in which some fields can be null
. For example:
class Foo { String bar; //.... }
I want to write a BarComparator for this class,
private static class BarComparator implements Comparator<Foo> { public int compare( final Foo o1, final Foo o2 ) { // Implementation goes here } }
Is there a standard way to deal with the fact that any of o1
, o2
, o1.bar
, o2.bar
can be null
, without writing lots of nested if
...else
?
Cheers!
You can't compare with NULL. You need is. null to test if something is a reference to the NULL object. @CarlesMitjans the variable is not always NULL, normally it has another integer value.
For comparison operators in SQL, NULL can be compared usingIS or IS NOT operator. SQL treats each NULL as a distinct value, so =,<,> can not beused for comparison.In general, NULL values are discarded when aggregate functions are applied to aparticular column.
To check for null variables, you can use a strict equality operator ( === ) to compare the variable with null . This is demonstrated below, where the boolean expression evaluates to true for only for null and evaluates to false for other falsy values.
Use <=> (null-safe equality operator) negated comparison which returns FALSE in case one of the operands is null but TRUE when both are null and both operands have equal non-null values.
I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:
static <T extends Comparable<T>> int cp(T a, T b) { return a==null ? (b==null ? 0 : Integer.MIN_VALUE) : (b==null ? Integer.MAX_VALUE : a.compareTo(b)); }
Simple usage (multiple fields is as you would normally):
public int compare( final Foo o1, final Foo o2 ) { return cp(o1.field, o2.field); }
Thanks for the replies! The generic method and the Google Comparators look interesting.
And I found that there's a NullComparator in the Apache Commons Collections (which we're currently using):
private static class BarComparator implements Comparator<Foo> { public int compare( final Foo o1, final Foo o2 ) { // o1.bar & o2.bar nulleness is taken care of by the NullComparator. // Easy to extend to more fields. return NULL_COMPARATOR.compare(o1.bar, o2.bar); } private final static NullComparator NULL_COMPARATOR = new NullComparator(false); }
Note: I focused on the bar
field here to keep it to the point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With