Bubolina Bubolina - 3 months ago 22
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

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) {
    System.out.println(value);
}

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.