Miki
Miki

Reputation: 103

Difference between an Array of null versus a null Array

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

Answers (3)

Turing85
Turing85

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:

  • a reference pointing to 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

Craig Tullis
Craig Tullis

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

Will Fisher
Will Fisher

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

Related Questions