方法的入参不能为null

时间:2025-04-09 08:37:34

缘由:

       某天,发现一段日志中出现了诡异的NPE。经过定位,认为是ArrayList不能加入null所致。

验证:

       new一个ArrayList,然后调用其addAll方法,并将入参设为null。

public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        (null);
        ("运行到此说明的参数可以为null。");
    }

实验结果为:

 

Exception in thread "main" 
	at (:581)
	at (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<>();
        (null);
        ("运行到此说明的参数可以为null。");
    }

来看下实验结果:

运行到此说明的参数可以为null。

Process finished with exit code 0

nice! No Problem,说明add方法完全是可以加入null的。

总结一下:

       日常编码中,如果ArrayList中要addAll,必须提前进行判null处理。而调用add则无须此操作。