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中文網其他相關文章!