Why Does java.util.ArrayList Allow Adding Null?

api-designcollectionsjava

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:

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.


Side note there is an auxiliary discussion in comments below, along with additional considerations supporting the reasoning laid out here.

Related Topic