Beancomparator不使用空值

时间:2013-01-28 18:03:46

标签: java

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

2 个答案:

答案 0 :(得分:13)

我这样使用它:

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

IMO更容易:)

答案 1 :(得分:1)

处理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());
}
}