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对象操作就会报错!
解决办法
法一:移除null元素
示例:
List<User> users = new ArrayList<User>(); users.add(null); users.add(null); users.add(null); System.out.println("size:"+users.size()); //size:3for(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); //移除第一个nullSystem.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); } }
<span style="font-size: 14px">法二:保证数据库查询出来没有null值,即遇null值转换为默认值<br><br><br></span><span style='font-family: "Microsoft YaHei"'>mysql下使用ifnull/case when均可实现</span><br><span style='font-family: "Microsoft YaHei"'>select ifnull(min(id),-1) as id,ifnull(min(name),'defaultName') as name from user where 1=2;</span>
(有group by是分组统计,找不到记录就是没有记录)
<br>
<span style="font-size: 14px"><em><br><br></em></span>
以上是list All elements are null引起的异常的详细内容。更多信息请关注PHP中文网其他相关文章!