Séb*_*rra 21 java comparison null
在Java中,我使用的是一些字段可以使用的类null.例如:
class Foo {
String bar;
//....
}
Run Code Online (Sandbox Code Playgroud)
我想为这个班写一个BarComparator,
private static class BarComparator
implements Comparator<Foo> {
public int compare( final Foo o1, final Foo o2 )
{
// Implementation goes here
}
}
Run Code Online (Sandbox Code Playgroud)
是否有应对的事实,任何的标准方式o1,o2,o1.bar,o2.bar可null,而无需编写大量的嵌套if...... else?
干杯!
Tom*_*ine 36
我猜你可以用一个小的静态方法来调用字段compareTo方法,以便对高或低的空值进行排序:
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));
}
Run Code Online (Sandbox Code Playgroud)
简单用法(多个字段与通常一样):
public int compare( final Foo o1, final Foo o2 ) {
return cp(o1.field, o2.field);
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的回复!通用方法和Google Comparators看起来很有趣.
而且我发现,有一个NullComparator中的Apache Commons Collections中(这是我们目前正在使用):
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);
}
Run Code Online (Sandbox Code Playgroud)
注意:我专注于bar这里的领域,以保持它的重点.
这取决于您是否将null条目视为值得比较的有效字符串值.是null <或>"apple".我唯一可以肯定的是null == null.如果您可以定义null适合排序的位置,那么您可以适当地编写代码.
在这种情况下,我可能会选择抛出NullPointerExcpetion或IllegalArgumentException,并尝试通过不首先将它放在比较中来处理更高级别的null.