Collection.add inserts one object as a single element. Use addAll when the intention is to insert every element from another collection; confusing the two leaves nested collections instead of flattening their contents. section 8.2
Accidentally adding a collection as one element
List<Object> result = new ArrayList<>(); result.add(getInitialValue()); result.add(getPredefinedValues()); result.add(getUserSpecifiedValues()); Here, each returned List becomes one element of result. Replace the latter calls with addAll(...) when their contents should be inserted individually. A List<Object> makes this mistake possible and can hold unrelated objects, including other collections. section 8.2
Table 8.1 Methods operating on a single object and collections
|
Single-object method
|
Collection method
|
|---|---|
list.add(object)
|
list.addAll(collection)
|
list.contains(object)
|
list.containsAll(collection)
|
list.remove(object)
|
list.removeAll(collection)
|
List.of(object)
|
List.copyOf(collection)
|
Stream.of(object)
|
collection.stream()
|
Compare single-object and collection-oriented pairs: add/addAll, contains/containsAll, remove/removeAll, List.of/List.copyOf, and Stream.of/stream. section 8.2
