Nulls in collections
Know exactly which collections accept null and which throw the moment they see one.
Open this lesson in the learning hubKey points
HashMapallows onenullkey and any number ofnullvalues.ArrayListallows nulls too.TreeMapandTreeSetrejectnullkeys, because they have to compare every key.ArrayDequeand the queues rejectnullbecausenullis their "nothing there" answer.List.of,Set.of,Map.ofandConcurrentHashMapbannulloutright.- A
nullfrommap.get(k)is ambiguous: absent, or present and null?containsKeyis the honest answer. - Sorting a list that contains nulls needs
Comparator.nullsFirstornullsLast, 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.