Nulls in collections

Collections · lesson 29 of 42 · 3 min read

Know exactly which collections accept null and which throw the moment they see one.

Open this lesson in the learning hub

Key points

  • HashMap allows one null key and any number of null values. ArrayList allows nulls too.
  • TreeMap and TreeSet reject null keys, because they have to compare every key.
  • ArrayDeque and the queues reject null because null is their "nothing there" answer.
  • List.of, Set.of, Map.of and ConcurrentHashMap ban null outright.
  • A null from map.get(k) is ambiguous: absent, or present and null? containsKey is the honest answer.
  • Sorting a list that contains nulls needs Comparator.nullsFirst or nullsLast, or you get an NPE.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, String> hash = new HashMap<>();
        hash.put(null, "one null key is allowed");
        hash.put("k", null);
        System.out.println("HashMap null key  : " + hash.get(null));
        System.out.println("get(k)            : " + hash.get("k") + "   (absent or mapped to null?)");
        System.out.println("containsKey(k)    : " + hash.containsKey("k") + "   (this is the honest answer)");

        try {
            new TreeMap<String, String>().put(null, "x");
        } catch (NullPointerException e) {
            System.out.println("TreeMap null key  : NullPointerException, it must compare keys");
        }
        try {
            new ArrayDeque<String>().add(null);
        } catch (NullPointerException e) {
            System.out.println("ArrayDeque null   : NullPointerException, null is its empty signal");
        }
        try {
            List.of("a", null);
        } catch (NullPointerException e) {
            System.out.println("List.of null      : NullPointerException, immutable factories ban null");
        }

        List<String> withNull = new ArrayList<>(Arrays.asList("b", null, "a"));
        System.out.println("ArrayList allows  : " + withNull + "   size " + withNull.size());
        withNull.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
        System.out.println("nullsFirst sort   : " + withNull);
    }
}

Nulls are allowed in the old collections and banned in the new ones. Assume banned and you will be fine.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.