5

我的要求是根据该 bean 中的customername属性对 Customer 类型的 bean 列表进行排序......因为我使用了它。当字段不是beancomparator时它工作正常。当场是投掷时..请帮帮我..customernamenullNullPointerExceptionnull

我的代码是

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...
}
4

2 回答 2

14

我这样使用它:

    Comparator<Customer> comparator = new BeanComparator(customername, new NullComparator(false));
    if (descentSort){
        comparator = new ReverseComparator(comparator);
    }
    Collections.sort(list, comparator);

IMO这是更简单的方法:)

于 2013-07-01T14:19:16.477 回答
2

处理您的无效检查的情况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());
}
}
于 2013-01-28T18:04:53.583 回答