BackendBench
Coffee
Spot the Bug #97

A list that cannot grow

A easy 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.

easyCollections contractsbuggy line: 6

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

What is wrong

Arrays.asList returns a fixed-size list backed by the array. It supports set, but add and remove throw UnsupportedOperationException.

The fix

List<String> tags = new ArrayList<>(Arrays.asList("java", "spring"));

How to avoid it next time

Wrap in new ArrayList when you need a modifiable list. List.of is immutable.

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โ† #96#98 โ†’

Frequently asked questions

What is the bug in "A list that cannot grow"?

Arrays.asList returns a fixed-size list backed by the array. It supports set, but add and remove throw UnsupportedOperationException. The faulty line is line 6: tags.add("kafka");

How do I fix it?

Replace it with: List tags = new ArrayList<>(Arrays.asList("java", "spring"));. Wrap in new ArrayList when you need a modifiable list. List.of is immutable.

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