liveBook · Manning

List.of

As explained in 100 Java Mistakes and How to Avoid Them

List.of is a Java library factory method that creates an unmodifiable list containing the supplied elements.

List.of creates a new unmodifiable list from supplied elements. The main trap is confusing a single collection element with the elements of that collection: List.of(values) can create a list containing values itself rather than a flattened list. section 8.2

Avoid these related mistakes when choosing collection APIs:

  • Use list.add(object) for one element and list.addAll(collection) for another collection's elements; List.of does not provide the mutating behavior of either method. section 8.2
  • Do not assume the List interface reveals null behavior. Lists returned by List.of reject null elements, and contains(null) can throw NullPointerException instead of returning false. section 8.3
  • Use obj != null && list.contains(obj) when the searched value may be null, and review such calls carefully when replacing older unmodifiable collections. section 8.3

A collection passed as one element

List<Object> createList(boolean userSpecifiedOnly) { if (userSpecifiedOnly) { return List.of(getUserSpecifiedValues()); } … } If getUserSpecifiedValues() returns a list, this construct can produce a list whose element is that list. Use the appropriate collection operation when the intended result is to include the contained values. section 8.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains factory semantics, nested-list mistakes, null-hostile searches, and migration precautions without detailing implementation internals.
Examples
Uses List.of(getUserSpecifiedValues()) and contrasts it with older and newer unmodifiable set declarations.
What it assumes
Assumes familiarity with Java collections, interfaces, generics, and method overload distinctions.
What you can do after
Diagnose accidental nesting and null-related failures, then choose single-object, collection, or null-safe APIs deliberately.
How it connects
Connects List.of with List.copyOf, add, addAll, contains, containsAll, Stream.of, collection.stream(), and unmodifiable collections.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.