List列表排序报空指针异常

  在项目中,想对列表数据按照日期字段排序,使用List.sort(Comparator c)方法,却总是报空指针异常。

  通过网上查询,得知该问题应该是List中有null值引起的。即ArrayList中的数组长度默认为10,如果对其添加值个数小于10,就会有null值存在。而sort()方法会遍历每个对象取该对象的日期字段,当对象为null时再取其日期字段值自然会报空指针异常。

  下面是网友的解决方法,新建一个同类型的ArrayList来装null,然后再从原List中removeAll该新List。这样一来原List中的null值就都不见了。排序也就不再报空指针异常了。原文:https://blog.csdn.net/liming_0820/article/details/77744240

List<CurriclumScheduleEntityModel> Nonlist = new ArrayList<CurriclumScheduleEntityModel>();  
Nonlist.add(null);  
listCellTime.remove(i);  
listCellTime.removeAll(Nonlist);

---------------------
作者:LiMing_0820 
来源:CSDN 
原文:https://blog.csdn.net/liming_0820/article/details/77744240?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

posted @ 2018-10-10 15:44  GreenMountain  阅读(1486)  评论(0编辑  收藏  举报