1. Overview

In this article, we’ll explore the tolerance and restrictions regarding null values in different Java collection types. Java collections handle null values differently, requiring careful attention.

While ArrayList and HashMap allow null values, accessing them risks NullPointerException. In contrast, TreeMap prohibits null keys entirely. Understanding these differences is crucial to avoid runtime errors, especially when using Streams or processing collections. Proper null-checking ensures robust and error-free code.

2. A null Value in a List

A List can include null elements. We can add and retrieve null values without errors. However, always check for null after retrieval to avoid a NullPointerException.

First, let’s define a reusable lambda expression to count null values in a collection:

Function<Collection<?>, Long> countNulls
    = collection -> collection.stream().filter(Objects::isNull).count();

The Function<Collection<?>, Long> interface defines a lambda expression that takes a Collection<?> and returns the count of null values. The stream() method converts the collection into a stream, filter(Objects::isNull) keeps only the null elements, and count() returns the number of those null elements.

Now, let’s test handling null values added to a list:

@Test
void givenList_whenNullValueAdded_doesNotFail() {
    // adding nulls to a list
    Integer[] numberArray = { null, 0, 1, null, 2, 3, null };
    List<Integer> numbers = Arrays.asList(numberArray);
    assertEquals(3, countNulls.apply(numbers));

    // accessing nulls from a list
    Integer number = numbers.get(0);
    assertNull(number);

    // dereferencing nulls from a list
    assertThrows(NullPointerException.class, () -> number.toString());
}

This test verifies that adding null values to a List does not cause an error. Then, the test verifies that our function accurately counts the number of null elements. Next, the test asserts that accessing null elements from the list returns null. Finally, it ensures that attempting to dereference a null (by calling a method on it) throws a NullPointerException.

3. A null Value in a Set

A Set consists of unique elements, meaning each element can only appear once. Also, a Set can contain at most one null value at a time. This characteristic ensures that no duplicates are allowed and helps maintain the integrity of the data.

Not all types of sets permit null values. Let’s explore the reasons behind this.

A HashSet can hold one null value. Backed by a HashMap, the hash-based lookup can handle a single null element. However, we need to be cautious about operations that may trigger NullPointerException if null is used in custom logic, such as hashing.

A TreeSet cannot hold null values because it relies on the Comparable or a custom Comparator. Any attempt to add null results in a NullPointerException as the natural ordering cannot compare null.

Let’s proceed to examine the management of null values within a Set. First, let’s check a HashSet:

@Test
void givenHashSet_whenNullValueAdded_doesNotFail() {
    // adding nulls to a HashSet
    Integer[] numberArray = { null, 0, 1, null, 2, 3, null };
    Set<Integer> numbers = new HashSet<>(Arrays.asList(numberArray));
    assertEquals(1, countNulls.apply(numbers));

    // accessing null from a set
    assertTrue(numbers.contains(null));

    // dereferencing nulls from a set
    assertThrows(NullPointerException.class, () -> numbers.forEach(Object::toString()));
}

Here, we confirm that adding null values to a HashSet does not result in an error. Then, we verify that duplicate null entries are ignored. We then check that the set correctly contains one null and that trying to dereference null within the set iteration throws a NullPointerException.

Now, it’s time to check how a TreeSet handles null values:

@Test
void givenTreeSet_whenNullValueAdded_mightFail() {
    // adding nulls to a TreeSet
    Integer[] numberArray = { null, 0, 1, null, 2, 3, null };
    assertThrows(NullPointerException.class, () -> new TreeSet<>(Arrays.asList(numberArray)));
}

This test demonstrates that adding null values to a TreeSet throws a NullPointerException. Remember that TreeSet requires elements to be comparable, and null cannot be compared during sorting.

4. A null Value in a Map

HashMap in Java is a data structure that allows for storing key-value pairs, accommodating one null key and multiple null values. This means that we can insert a single null key, and at the same time, we can associate multiple null values with other keys. When the null key is added, it is specifically stored in a designated hash bucket reserved for null keys.

When using the get() method to retrieve a value associated with a null key, the HashMap gracefully handles this case without throwing any exceptions, making it straightforward for developers to work with null keys.

However, it’s important to be cautious when dereferencing these null keys and values in our code, as attempting to operate on null references can lead to NullPointerException. Therefore, proper checks should be implemented to ensure we’re managing null values effectively to prevent runtime errors:

@Test
void givenHashMap_whenNullKeyValueAdded_doesNotFail() {
    // adding nulls to key-value pairs
    Integer[] numberArray = { null, 0, 1, null, 2, 3, null };
    Map<Integer, Integer> numbers = new HashMap<>();
    Arrays.stream(numberArray)
        .forEach(integer -> numbers.put(integer, integer));
    assertEquals(1, countNulls.apply(numbers.keySet()));
    assertEquals(1, countNulls.apply(numbers.values()));

    // accessing nulls from a map
    assertTrue(numbers.containsKey(null));
    assertTrue(numbers.containsValue(null));
    assertNull(numbers.get(null));

    // dereferencing nulls from a map
    assertThrows(NullPointerException.class, () -> numbers.get(null)
        .toString());
}

In the above test, we verify that adding null keys and values to a HashMap does not cause errors, demonstrating HashMap’s ability to handle null as both a key and a value. We also check behaviors for the presence of null keys and values, confirm retrieval of null, and assert that dereferencing null triggers a NullPointerException.

Now, it’s time to check how a TreeMap handles null values:

@Test
void givenTreeMap_whenNullKeyAdded_fails() {
    // adding nulls to key-value pairs
    Map<Integer, Integer> numbers = new TreeMap<>();

    // adding null key and null value
    assertThrows(NullPointerException.class, () -> numbers.put(null, null));

    // adding null key and non-null value
    assertThrows(NullPointerException.class, () -> numbers.put(null, 1));

    // adding non-null key and null value
    assertDoesNotThrow(() -> numbers.put(1, null));

    // adding non-null key and non-null value
    assertDoesNotThrow(() -> numbers.put(1, 1));
}

Here, we demonstrate that a TreeMap throws a NullPointerException when trying to add a null key, whether or not the value is null. However, we can see that it allows null values if the key is non-null*.*

5. Conclusion

In this article, we explored how Java collections handle null values, from ArrayList‘s and HashSet‘s flexibility to TreeMap’s strict restrictions. Understanding these behaviors helps prevent errors, ensuring safer data handling and more reliable applications.

As usual, all the code samples are available over on GitHub.