This small program
public class Client {
public static void main(String[] args) throws Exception {
Arrays.asList(null);
}
}
throws a NullPointerException
.
Exception in thread "main" java.lang.NullPointerException
at java.base/java.util.Objects.requireNonNull(Objects.java:221)
at java.base/java.util.Arrays$ArrayList.<init>(Arrays.java:4322)
at java.base/java.util.Arrays.asList(Arrays.java:4309)
at org.example.Client.main(Client.java:10)
This program, however,
public static void main(String[] args) throws Exception {
Arrays.asList(returnNull());
}
private static Object returnNull(){
return null;
}
does not. Why do they behave differently?
asList() doesn't return null or throw Exception.
The method only creates a List wrapper upon the underlying array. Because of which, both the array and the newly created list continue to refer to the exact same elements. That is why, no elements are copied when we use asList method.
Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it. The list will throw an UnsupportedOperationException if any resize operation is performed on it.
The asList() method of java. util. Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.
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.
Signature of asList() is :- public static <T> List<T> asList(T... a)
So args requires Array of type T.
1st Case: When you put null
as arg in asList the array will be pointing to null therefore throwing Exeption.
2nd Case: When you return a reference to any object which is pointing to null
. Then it means array having a single Object, and that Object is pointing to null
therefore not throwing Exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With