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!
I guess you could wrap the call to the field compareTo method with a small static method to sort nulls high or low:
Simple usage (multiple fields is as you would normally):