Collection.addAll inserts every element from another collection. The common mistake is using add(), which inserts the collection itself as one element instead of adding its contents. section 8.2
Accidentally nesting a collection
List<Object> result = new ArrayList<>(); result.add(getInitialValue()); result.add(getPredefinedValues()); result.add(getUserSpecifiedValues()); When the latter methods return lists, result contains those lists as elements. Use result.addAll(getPredefinedValues()) and result.addAll(getUserSpecifiedValues()) when the intended result is one list containing their values. section 8.2
Avoid related single-object and collection-method mix-ups:
- Use add(object) for one element and addAll(collection) for another collection. section 8.2
- Check contains versus containsAll and remove versus removeAll; Object-typed parameters can let the wrong call compile. section 8.2
- Prefer specific collection types over List<Object>, which permits unrelated objects and nested 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 methods with their collection-oriented counterparts, including add/addAll, contains/containsAll, and remove/removeAll. section 8.2
