我的要求是根据该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...
}
答案 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());
}
}