What to do with null fields in compare()?
问题 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! 回答1: I guess you could wrap the call to the