我的要求是根据该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/

10-12 00:24
查看更多