Explain null array java.

314    Asked by Amitraj in Java , Asked on Oct 6, 2022

 I wonder why java.util.ArrayList allows adding null. Is there any case where I would want to add null to an ArrayList?


I am asking this question because in a project we had a bug where some code was adding null to the ArrayList and it was hard to spot where the bug was. Obviously a NullPointerException was thrown but not until other code tried to access the element. The problem was how to locate the code that added the null object. It would have been easier if ArrayList threw an exception in the code where the elements were being added.

Answered by Andrea Bailey

This design decision appears mostly driven by naming.


Name ArrayList suggests to readers a functionality similar to arrays - and it is natural for null array Java Collections Framework designers to expect that the vast majority of API users will rely on it functioning similar to arrays. This in particular, involves treatment of null elements. API user knowing that below works OK:

  array[0] = null; // NPE won't happen here

would be quite surprised to find out if similar code for ArrayList would throw NPE:

  arrayList.set(0, null); // NPE => WTF?

Reasoning like above is presented in JCF tutorial stressing points that suggest close similarity between ArrayList and plain arrays:

  ArrayList... offers constant-time positional access and is just plain fast...

If you would want a List implementation disallowing nulls, it would better be called like NonNullableArrayList or something like that, to avoid confusing API users.



Your Answer

Interviews

Parent Categories