Reputation: 103
Given the code below:
List<Object> arrayList = new ArrayList<Object>();
for(int counter=0; counter < 100; counter++) {
arrayList.add(null);
}
Aside from the instantiated and having the size 100, how different "arrayList" from a List which is actually null?
Just curious.
Thanks.
Upvotes: 1
Views: 130
Reputation: 20185
First things first: an ArrayList<...>
is not an array, the ArrayList
is quite more sophisticated, but uses an array as backing datastructure.
Now to your question: The two main differences which come to my mind are those:
null
consumes much less memory than an actual ArrayList
of size 100. Note that the references are of same size, but the reference pointing to null
does not point to allocated memory. For the ArrayList
with 100 null
entries, all references to the 100 emelemts do exist, but refernce to null
, making it consume more memory.you cannot call methods on null
:
List<Object> list1 = new ArrayList<Object>(100);
list1.size(); // totally fine, will return 0
List<Object> list2 = null;
list2.size(); // throws a NullPointerException
Upvotes: 1
Reputation: 10497
Very simple. If you have an ArrayList
which is null, it is just a null object reference like any other (with a specific type assigned to it).
If you have an ArrayList
of 100 null elements, then it is a fully instantiated ArrayList
encapsulating 100 null object references.
Functionally, you can refer to any of those 100 null references without generating an exception. Whereas with a null ArrayList
, any attempt to access a specific member of the list will generate an exception.
In practice, just as a backgrounder, it is generally a good idea to return an instantiated collection from any method that returns a collection. It enables calling code to generically enumerate the collection even if it contains zero instances of whatever it is supposed to contain. Of course, opinions may vary. ;-)
Upvotes: 1
Reputation: 413
A list will be null if its variable has been defined but has not been declared as a new ArrayList.
List<String> nullList;
List<String> emptyList = new ArrayList<String>();
//empty list has been defined as a new ArrayList so it is not null, however it is empty because it has no elements
emptyList.add(null);
//empty list is still empty since all values are null
So when doing this:
nullList == null
would return true, but:
emptyList == null
would return false
Upvotes: 0