I wonder why java.util.ArrayList
allows to add 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 was being added.
Best Answer
This design decision appears mostly driven by naming.
Name ArrayList suggests to reader a functionality similar to arrays - and it is natural for Java Collections Framework designers to expect that 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:
would be quite surprised to find out if similar code for ArrayList would throw NPE:
Reasoning like above is presented in JCF tutorial stressing points that suggest close similarity between ArrayList and plain arrays:
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.Side note there is an auxiliary discussion in comments below, along with additional considerations supporting the reasoning laid out here.