Pitfall - Using null to represent an empty array or collection

suggest change

Some programmers think that it is a good idea to save space by using a null to represent an empty array or collection. While it is true that you can save a small amount of space, the flipside is that it makes your code more complicated, and more fragile. Compare these two versions of a method for summing an array:

The first version is how you would normally code the method:

/**
 * Sum the values in an array of integers.
 * @arg values the array to be summed
 * @return the sum
 **/
public int sum(int[] values) {
    int sum = 0;
    for (int value : values) {
        sum += value;
    }
    return sum;
}

The second version is how you need to code the method if you are in the habit of using null to represent an empty array.

/**
 * Sum the values in an array of integers.
 * @arg values the array to be summed, or null.
 * @return the sum, or zero if the array is null.
 **/
public int sum(int[] values) {
    int sum = 0;
    if (values != null) {
        for (int value : values) {
            sum += value;
        }
    }
    return sum;
}

As you can see, the code is a bit more complicated. This is directly attributable to the decision to use null in this way.

Now consider if this array that might be a null is used in lots of places. At each place where you use it, you need to consider whether you need to test for null. If you miss a null test that needs to be there, you risk a NullPointerException. Hence, the strategy of using null in this way leads to your application being more fragile; i.e. more vulnerable to the consequences of programmer errors.


The lesson here is to use empty arrays and empty lists when that is what you mean.

int[] values = new int[0];                     // always empty
List<Integer> list = new ArrayList();          // initially empty
List<Integer> list = Collections.emptyList();  // always empty

The space overhead is small, and there are other ways to minimize it if this this is a worthwhile thing to do.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents