Video in progress

Strong Middle 🧺 Collections

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:

  1. A method returns Collections.emptyList() when empty and an ArrayList otherwise. The caller does add on the result and fails only in the empty case. Tests usually check the full case, so the bug reaches prod.

  2. nCopies with 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.

  1. The null difference: singletonList(null) and nCopies(3, null) allow it, while List.of((Object) null) throws an NPE. When you migrate old code to List.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.