Bubolina Bubolina - 1 year ago 81
Java Question

Arrays.asList(value, null); - is this OK?

Is it OK to create a List of Objects and insert directly a null one like this:

Integer in = 123;
Integer in2 = null;
List<Integer> things = Arrays.asList(in, in2);

Answer Source

You can do that but you need to be careful then with unboxing, indeed because of unboxing a simple code like the following one will throw an NPE

for (int value : things) {

The previous code throws an NPE while iterating over the list because as the expected type is the primitive type int and not the wrapper class Integer, to convert the value to an int, it will automatically call behind the scene intValue() on the current Integer instance so if it is null it will throw an NPE.

More generally speaking, you will need to deal with null values properly to prevent NPE which will make your code harder to read and maintain.