Why does Arrays.asList(null) throw a NullPointerException while Arrays.asList(someNullVariable) does not?
The difference is just about how the argument is used at runtime:
The signature of asList
is
public static <T> List<T> asList(T... a)
Arrays.asList(returnNull())
calls it with an Object
. This clearly does not get interpreted as an array. Java creates an array at runtime and passes it as an array with one null
element. This is equivalent to Arrays.asList((Object) null)
However, when you use Arrays.asList(null)
, the argument that's passed is taken to be an array, and, as the the method explicitly fails on null arrays passed as argument (see java.util.Arrays.ArrayList.ArrayList(E[])
), you get that NPE.