Video in progress
What do Collections.emptyList(), singletonList() and nCopies() return, and what mistakes come up with them?
All three return an immutable, lightweight list: emptyList is a single shared instance, singletonList is an object with one field, and nCopies doesn't store the element n times, only one reference and a count. If you add to them you get an UnsupportedOperationException.
📖 Answer
These methods appeared long before List.of and still show up in plenty of code.
List<String> none = Collections.emptyList();
List<String> one = Collections.singletonList("admin");
List<String> dash = Collections.nCopies(1_000_000, "-"); // a million elements, but one reference
There is no array inside nCopies; get(i) always returns that same single object. That makes it handy for filling: new ArrayList<>(Collections.nCopies(n, 0)) gives a mutable list of n zeros, or String.join("", Collections.nCopies(3, "ab")).
Common mistakes:
-
A method returns
Collections.emptyList()when empty and anArrayListotherwise. The caller doesaddon the result and fails only in the empty case. Tests usually check the full case, so the bug reaches prod. -
nCopieswith a mutable object:
List<List<Integer>> rows = new ArrayList<>(Collections.nCopies(3, new ArrayList<>()));
rows.get(0).add(1);
System.out.println(rows); // [[1], [1], [1]] — all three are the same list
The right way is to create a separate new ArrayList<>() for each row in a loop.
- The null difference:
singletonList(null)andnCopies(3, null)allow it, whileList.of((Object) null)throws an NPE. When you migrate old code toList.of, this is exactly where it fails.
set doesn't work on singletonList either. In new code I use List.of() and List.of(x), and nCopies has no direct replacement.
Sign up to mark studied questions and save your progress.