liveBook · Manning

Collection.addAll

As explained in 100 Java Mistakes and How to Avoid Them

Collection.addAll is a Java Collection operation that inserts all elements from another collection.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the nesting consequence and compilation risks, but does not develop implementation internals.
Examples
Uses a List<Object> assembled from an initial value, predefined values, and user-specified values.
What it assumes
Assumes familiarity with Java collections, generic types, and method arguments.
What you can do after
Apply Collection.addAll correctly and diagnose accidental nested collections caused by add().
How it connects
Connects Collection.addAll with Collection.add, containsAll, removeAll, List.copyOf, and collection.stream().

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.