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.
null
in most of their collections).null
is the default way to represent missing data in Java, whether you like it or not. In fact a lot of people don't like it and make it an argument for functional programming-style things. The most upvoted answer makes no sense/doesn't capture the essence of the issue.null
is. "Missing" is just one of several potential interpretations ofnull
. Other valid interpretations could be "Unknown," "Not Applicable," or "Uninitialized." Whatnull
represents depends on the application. As the Python community would say, "In the face of ambiguity, refuse the temptation to guess." Refusing to hold null in a container that is perfectly capable of doing so would be just that--a guess.