缘由:
某天,发现一段日志中出现了诡异的NPE。经过定位,认为是ArrayList不能加入null所致。
验证:
new一个ArrayList,然后调用其addAll方法,并将入参设为null。
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.addAll(null);
System.out.println("运行到此说明list.addAll的参数可以为null。");
}
实验结果为:
Exception in thread "main" java.lang.NullPointerException
at java.util.ArrayList.addAll(ArrayList.java:581)
at Scratch.main(scratch_2.java:7)
Process finished with exit code 1
可以看到,addAll是不能加入null的。
具体原理就不在深究了,感兴趣的可以debug进去看一下。
那么,addAll既然不能加入null,add是否也不能加入null呢?一起来验证一下:
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add(null);
System.out.println("运行到此说明list.add的参数可以为null。");
}
来看下实验结果:
运行到此说明list.add的参数可以为null。
Process finished with exit code 0
nice! No Problem,说明add方法完全是可以加入null的。
总结一下:
日常编码中,如果ArrayList中要addAll,必须提前进行判null处理。而调用add则无须此操作。
博客讲述了因日志出现NPE,定位到ArrayList添加元素问题。经实验,addAll方法不能加入null,add方法可以加入null。提醒日常编码中,ArrayList使用addAll需提前判null,使用add则无需。
1041

被折叠的 条评论
为什么被折叠?



