BackendBench
Coffee
Spot the Bug #98

An immutable list with a missing element

A medium Java puzzle in the collections contracts family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumCollections contractsbuggy line: 5

Highlighted: line 5. Play this one as a puzzle without the answer.

What is wrong

List.of, Set.of and Map.of reject null elements with NullPointerException. The call fails whenever the optional backup is missing, which may not happen in tests.

The fix

return Stream.of(primary, backup).filter(Objects::nonNull).toList();

How to avoid it next time

Filter or validate null before building immutable collections.

Want the background? Read Collections: List, Set, Map in the Java concepts library.

About collections contracts

Collection classes come with contracts about ordering, mutability and key behavior. Fixed-size lists, views of other collections and mutable map keys break those contracts without compile errors.

In code review: Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #97#99 โ†’

Frequently asked questions

What is the bug in "An immutable list with a missing element"?

List.of, Set.of and Map.of reject null elements with NullPointerException. The call fails whenever the optional backup is missing, which may not happen in tests. The faulty line is line 5: return List.of(primary, backup);

How do I fix it?

Replace it with: return Stream.of(primary, backup).filter(Objects::nonNull).toList();. Filter or validate null before building immutable collections.

How do I catch collections contracts in code review?

Check what the factory method returns, whether the result is modified later, and whether objects used as keys can change after insertion.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need