list All elements are null引起的异常,elementsnull
ArrayList允许添加null值,就容易造成了list内的对象转换出现java.lang.NullPointerException异常。
场景:
数据库 select min(id) as id,min(name) as name from user where 1=2;
查询出的不是没有记录,而是一条 null,null这样的记录,导致User对象为null
List<User> users = useDao.find(xxx); //size=1,All elements are null
这时候对user对象操作就会报错!
解决办法
法一:移除null元素
示例:
List<User> users = new ArrayList<User>(); users.add(null); users.add(null); users.add(null); System.out.println("size:"+users.size()); //size:3 for(User user:users){ try { System.out.println("id:" + user.getId() + ",name:" + user.getName()); }catch (Exception ex){ System.out.println(ex); //java.lang.NullPointerException } } users.remove(null); //移除第一个null System.out.println("size:"+users.size()); //size:2 users.removeAll(Collections.singleton(null)); //移除所有的null元素 System.out.println("size:"+users.size()); //size:0 //不会进入循环 for(User user:users){ try { System.out.println("id:" + user.getId() + ",name:" + user.getName()); }catch (Exception ex){ System.out.println(ex); } }
法二:保证数据库查询出来没有null值,即遇null值转换为默认值 mysql下使用ifnull/case when均可实现 select ifnull(min(id),-1) as id,ifnull(min(name),'defaultName') as name from user where 1=2;
select case when min(id) is null then -1 else min(id) end as id,case when min(name) is null then 'defaultName' else min(name) end as name from user where 1=2; 这样子查询出来的结果如下 id name -1 defaultName 总结:具体情况依据业务实现,当对数据库查询统计的时候,没有group by关键字而使用聚集函数的时候一定要注意null