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
