我的要求是根据该bean中的customername
属性对Customer类型bean的列表进行排序...为此,我使用了beancomparator
。当customername
字段不是null
时,它工作正常。
当字段是NullPointerException
时,它会抛出null
..请帮帮我。
我的代码是
public class customer{
private String customername;
}
main()
{
list<customer> list=new arraylist();
//list is filled with customertype beans
comparator<customer> comp=new beancomparator(customername);
collections.sort(list,comp);//throwing error when customername is null...
}
最佳答案
在Comparator
中处理无效检查的情况
new Comparator<Customer>() {
public int compare(Customer o1, Customer o2) {
if(o1.getName() == null){ return -1;}
if(o2.getName() == null){ return 1;}
return o1.getName().compareTo(o2.getName());
}
}
关于java - Beancomparator无法使用空值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14568266/