liveBook · Manning

Add method

As explained in 100 Java Mistakes and How to Avoid Them

Collection.add is a Java Collection operation that inserts a single element into a collection.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the API distinction, nested-collection consequence, and risks of List<Object>, but does not detail implementation internals.
Examples
Uses a List<Object> factory whose add calls place predefined and user-specified lists inside the result.
What it assumes
Assumes familiarity with Java collections, generic lists, and the distinction between objects and collections.
What you can do after
Diagnose nested-collection results and choose add or addAll according to the intended element shape.
How it connects
Connects add with addAll, contains, containsAll, remove, removeAll, List.of, List.copyOf, Stream.of, and 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.