skip to content

What are the null-element and duplicate-element rules of List.of / Set.of / Map.of, and how do they differ from ArrayList/HashSet/HashMap?

level: middleimportance: should knowfreq 58%

answer

  1. Null anywhere -> NPE (all three factories)
  2. Set.of duplicate / Map.of duplicate key -> IllegalArgumentException
  3. List.of CAN hold duplicate values
  4. ArrayList keeps duplicates; HashSet dedupes; HashMap overwrites
  5. Strictness = fail fast for fixed data

basics

~20 s

List.of, Set.of and Map.of refuse nulls with NullPointerException; Set.of and Map.of also throw IllegalArgumentException on duplicate elements or keys. ArrayList stores nulls and duplicates; HashSet allows one null and ignores duplicates; HashMap allows one null key and overwrites.

solid answer

~50 s

Factory collections are deliberately strict. A null element in List.of/Set.of, or a null key or value in Map.of, throws NullPointerException at construction, and lookups refuse null too: List.of(1).contains(null) throws. Set.of with a repeated element and Map.of with a repeated key throw IllegalArgumentException — they fail fast rather than silently collapsing; List.of may hold duplicates. This contrasts with the classic collections: ArrayList allows multiple nulls and duplicates; HashSet allows a single null and just ignores a duplicate add; HashMap allows one null key, null values, and silently overwrites on a duplicate key. JEP 269 gives the reason for the null rule: a more compact representation, faster access, and fewer special cases. If you genuinely need nulls or last-write-wins semantics, use the traditional collections; Stream.toList (Java 16) also permits nulls, and Set.copyOf keeps one of any duplicates.

code

java · 11 lines
java
List.of("a", "a");           // OK - lists allow duplicates
Set.of("x", "x");            // IllegalArgumentException - duplicate element
Map.of("k", 1, "k", 2);      // IllegalArgumentException - duplicate key

List.of("a", null);          // NullPointerException
Map.of("k", null);           // NullPointerException (null value)
Map.of(null, "v");           // NullPointerException (null key)

// Classic collections stay silent:
Set<String> s = new HashSet<>();
s.add("x"); s.add("x");       // second ignored, no error

go deeper

for a junior

Knows factories reject null and that the result cannot be changed.

for a middle

Distinguishes NPE for nulls from IllegalArgumentException for Set/Map duplicates, and contrasts with lenient HashSet/HashMap behavior.

for a senior

Explains the fail-fast rationale and when null/duplicate tolerance means choosing classic collections instead.

for a principal

Uses these guarantees in API contracts and validation strategy; reasons about null-hostility as a design choice across the codebase.

## Background terms - *Element*: a value stored in a `List` or `Set`. - *Key/value*: in a `Map`, each entry is a key (the lookup handle) mapped to a value. - *Duplicate*: in a `Set`, two elements that are `equals()`; in a `Map`, two entries with `equals()` keys. - *NullPointerException (NPE)*: thrown when code uses a `null` where an object is required. - *IllegalArgumentException (IAE)*: thrown when a method receives an argument that is invalid for it. - *Fail fast*: detect and report a problem at the earliest possible moment (here, at construction) instead of letting it silently corrupt later behavior. ## The classic collections are lenient ```java List<String> a = new ArrayList<>(); a.add(null); a.add(null); // fine: two nulls allowed Set<String> s = new HashSet<>(); s.add("x"); s.add("x"); // second add ignored, no error s.add(null); // one null allowed Map<String,String> m = new HashMap<>(); m.put("k", "1"); m.put("k", "2"); // silently overwrites: k -> 2 m.put(null, "v"); // one null key allowed ``` Nothing throws. Duplicates and nulls are tolerated. ## The factory collections are strict ```java List.of("a", null); // NullPointerException Set.of("x", "x"); // IllegalArgumentException: duplicate element Map.of("k", "1", "k", "2"); // IllegalArgumentException: duplicate key Map.of("k", null); // NullPointerException Map.of(null, "v"); // NullPointerException ``` Every rule is enforced *at the moment you build the collection*. A repeated key throws even when its values are equal: `Map.of("k", 1, "k", 1)`. ## Lookups refuse null too The null rule reaches past construction. `List.of(1).contains(null)`, `Set.of(1).contains(null)`, `Map.of(1, 1).containsKey(null)` and `Map.of(1, 1).get(null)` all throw `NullPointerException`, where an `ArrayList` or `HashMap` just answers `false` or `null`. The `Collection` contract marks that exception optional for `contains`, so both behaviors conform. It bites when a factory list replaces an `ArrayList` behind code that probes for null. ## Why the strictness 1. **Bug surfacing.** These collections are meant for small, fixed data. A duplicate in a literal `Set.of(...)` usually means a typo, and failing fast turns a silent logic bug into an immediate, obvious exception. That is the practical payoff; the spec itself states only the rule: "They reject duplicate elements at creation time." 2. **No-null simplicity.** This one is JEP 269's own reason: "prohibiting nulls offers opportunities for a more compact internal representation, faster access, and fewer special cases." It also removes an ambiguity ("does this map hold a null value, or is the key absent?"). 3. **Immutability fit.** Because no element can be added or replaced later, the only chance to catch a bad input is at construction — so they check thoroughly there. ## A subtle point: List.of allows value-duplicates A `List` is *allowed* to contain duplicates by definition, so `List.of("a", "a")` is perfectly legal — only `Set.of` and `Map.of` (keys) reject duplicates. The null rule, however, applies to all three. ## Neighbours with different rules - `Set.copyOf` (Java 10) tolerates duplicates: "an arbitrary element of the duplicates is preserved", so `Set.copyOf(List.of(1, 1))` is `[1]`. Nulls in the source still throw, as they do for `List.copyOf` and `Map.copyOf`. - `Stream.toList()` (Java 16) returns an unmodifiable list that **permits** null: `Stream.of(1, null).toList().contains(null)` is `true`. - `Collections.singletonList(null)` is legal as well, so null-hostility belongs to these factories, not to every small collection. ## When to avoid the factories If your data legitimately needs `null` (e.g., a list with intentional gaps) or you want last-write-wins map semantics, use `ArrayList`/`HashMap` (optionally wrapped) instead. The factories are the wrong tool when null or duplicate-tolerance is a feature.

  • Does List.of("a", "a") throw?
    No. A List may contain duplicate values, so this is allowed. Only Set.of (duplicate element) and Map.of (duplicate key) throw IllegalArgumentException.
  • What exception does Map.of("k", null) throw and when?
    NullPointerException, thrown immediately at construction, because null values are not permitted in factory maps.

  • Thinking Set.of("x","x") silently dedupes like HashSet
  • Assuming Map.of overwrites on duplicate key (it throws)
  • Believing List.of forbids duplicate values (it allows them)
  • Expecting List.of, Set.of or Map.of to accept a null
  • Expecting List.of(1).contains(null) to return false

List.of, Set.of and Map.of
Java 9

Assumes JDK 27, the same at JDK 25. The null and duplicate rules date from Java 9; copyOf arrived in 10 and Stream.toList in 16.

context