ItArrayList
allows null by design. It is intentional. From the javadoc:
"[ArrayList is a] resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null."
The answer to "why" is that if it didn't the ArrayList wouldn't be usable in cases where it is necessary to put a null
in the list. By contrast, you can prevent an ArrayList from containing nulls by either testing values before adding them or using a wrapper that prevents this happening.
Is there any case where I would want to add null to an ArrayList?
Obviously, any case where null
has a distinct meaning. For instance it might mean that the value at a given position in the list has not been initialized or supplied.
It would have been easier if the ArrayList had thrown an exception in the code where the elements was being added.
You could have implementedeasily implement that usingbehaviour by creating a wrapper class. However, this is not the behaviour that most programmers / applications need.