What are the Collection bulk operations (addAll, removeAll, retainAll, containsAll, clear), and what set-like semantics do they implement?
answer
- addAll=union on Sets, removeAll=difference, retainAll=intersection
- containsAll=subset test (read-only)
- clear=empty, returns void
- addAll/removeAll/retainAll return 'did it change?'
- pass a Set to removeAll/retainAll for O(1) contains
basics
~20 sBulk operations act on many elements at once: addAll adds another collection's elements (union on a Set), removeAll deletes those also in it (difference), retainAll keeps only those (intersection), containsAll tests for a subset, and clear empties the collection.
solid answer
~50 sCollection's bulk operations act on many elements in one call, and four of them mirror set algebra. addAll(c) adds all of c's elements: a union when both are Sets, plain appending on a List. removeAll(c) removes every element also in c (difference). retainAll(c) keeps only elements also in c (intersection). containsAll(c) tests whether this collection holds every element of c (a subset test) without mutating. clear() removes everything. addAll, removeAll and retainAll return true if this collection changed, which is useful in loops; clear returns void. All but containsAll are optional operations, so they can throw UnsupportedOperationException, though a call that changes nothing need not. A classic gotcha: on an ArrayList, removeAll/retainAll call contains on the argument per element, so passing a List with O(n) contains makes them O(n*m) - pass a Set for performance.
code
java · 20 linesList<Integer> a = new ArrayList<>(List.of(1, 2, 3, 4));
List<Integer> b = List.of(3, 4, 5);
List<Integer> appended = new ArrayList<>(a);
appended.addAll(b); // List appends -> [1, 2, 3, 4, 3, 4, 5]
Set<Integer> union = new TreeSet<>(a);
union.addAll(b); // Set union -> [1, 2, 3, 4, 5]
List<Integer> diff = new ArrayList<>(a);
diff.removeAll(b); // difference -> [1, 2]
List<Integer> inter = new ArrayList<>(a);
inter.retainAll(b); // intersection -> [3, 4]
boolean subset = a.containsAll(List.of(2, 3)); // true (read-only)
// Performance: make the argument a Set for big removeAll/retainAll
Set<Integer> bSet = new HashSet<>(b);
inter.retainAll(bSet); // contains() is O(1) on averagego deeper
Knows the five methods exist and roughly what each does (add many, remove many, keep common, check all present, empty).
Maps each to a set operation, knows addAll, removeAll and retainAll return a changed-boolean, and that containsAll is read-only.
Articulates the O(n*m) contains() performance trap and the Set-argument fix, plus UnsupportedOperationException on unmodifiable collections.
Reasons about when to use bulk ops vs streams for clarity/perf, the AbstractCollection default-implementation behavior, and concurrency implications of bulk mutation on shared collections.
## What "bulk operations" means Most `Collection` methods touch **one** element (`add(e)`, `remove(e)`, `contains(e)`). The **bulk operations** act on many at once: four take **another whole collection** as the argument, and `clear()` takes none. Those four map onto **set algebra** (think Venn diagrams), exactly so when both collections are `Set`s. `this` is the collection you call the method on; `c` is the argument. ### 1. `boolean addAll(Collection<? extends E> c)` - UNION (on Sets) Adds every element of `c` into `this`. For a `List` it appends (duplicates fine); for a `Set` it adds only the new ones. Returns `true` if `this` changed as a result. ```java a.addAll(b); // on Sets, a becomes a ∪ b ``` ### 2. `boolean removeAll(Collection<?> c)` - DIFFERENCE Removes from `this` **every element that is also in `c`** (relative complement, `this \ c`). Returns `true` if anything was removed. ```java a.removeAll(b); // a becomes a − b ``` ### 3. `boolean retainAll(Collection<?> c)` - INTERSECTION Keeps in `this` **only** the elements that are **also in `c`**, removing all others (`this ∩ c`). Returns `true` if `this` changed. ```java a.retainAll(b); // a becomes a ∩ b ``` ### 4. `boolean containsAll(Collection<?> c)` - SUBSET TEST Returns `true` if `this` contains **every** element of `c` (i.e. `c ⊆ this`). It is **read-only** - it never mutates. ```java if (a.containsAll(b)) { /* b is a subset of a */ } ``` ### 5. `void clear()` - EMPTY Removes **all** elements, leaving `this` empty (size 0). Returns nothing. ### Also: `removeIf(Predicate)` Added in Java 8, it sits in the `// Bulk Operations` block of the `Collection` source. It takes a condition rather than a collection and returns `true` if anything was removed. ## Exact for Sets, looser for Lists The `Set` Javadoc names union, intersection and asymmetric difference only "If the specified collection is also a set". On a `List`, duplicates survive: - `addAll` appends: `[1, 2, 3, 4]` plus `[3, 4, 5]` gives `[1, 2, 3, 4, 3, 4, 5]`, not a union. - `retainAll` keeps every occurrence: `[1, 1, 2]` retaining `[1]` gives `[1, 1]`. - `containsAll` ignores counts: `[1]` contains all of `[1, 1]`. ## The boolean return value `addAll`, `removeAll` and `retainAll` return a **`boolean`** that answers *"did this collection change?"*. `false` means the operation had no effect (e.g. `retainAll` when everything was already retained). This is handy for fixed-point loops. ## Exceptions to expect - **`UnsupportedOperationException`** - `addAll`, `removeAll`, `retainAll` and `clear` are optional operations, and **unmodifiable** collections (e.g. `List.of(...)`, `Collections.unmodifiableList(...)`) throw this. The `Collection` Javadoc says such methods "should (but are not required to)" throw when the call would have no effect, so some don't: `Arrays.asList(1, 2).removeAll(List.of(3))` just returns `false`. - **`NullPointerException`** - if `c` is `null`. Beyond that the direction depends on the method. `addAll` and `containsAll` are about `c` holding a `null` that `this` forbids. `removeAll` and `retainAll` are about `this` holding a `null` that `c` doesn't support: `new ArrayList<>(Arrays.asList(1, null)).removeAll(List.of(1))` throws, because `List.of(1).contains(null)` does. - **`ClassCastException`** - the same split (rare): `addAll` and `containsAll` look at the elements of `c`, `removeAll` and `retainAll` at the elements of `this`. ## Performance gotcha (the interview favorite) In `ArrayList` and `AbstractCollection`, `removeAll(c)` and `retainAll(c)` iterate `this` and call **`c.contains(element)`** for each one. If `c` is a **`List`**, `contains` is **O(n)**, so the whole operation is **O(n*m)**. If `c` is a **`HashSet`**, `contains` is **O(1)** on average, so it drops to **O(n)**. Rule of thumb: *the argument to removeAll/retainAll should be a Set when it's large.* That is implementation, not interface contract. `AbstractSet.removeAll`, which `HashSet` inherits, iterates whichever side is smaller, so it may never call `c.contains`; when the set is the smaller side it does, and a big `List` argument still costs O(n*m). Also, `list.removeAll(list)` is just a slow `clear()`, and a subtle case: `AbstractCollection`'s `removeAll` removes through the iterator's `remove`, so an iterator without one throws `UnsupportedOperationException` only once an element actually matches. ## Quick mapping | Method | Set op | Mutates? | Returns | |---|---|---|---| | `addAll` | union (on Sets) | yes | changed? | | `removeAll` | difference | yes | changed? | | `retainAll` | intersection | yes | changed? | | `containsAll` | subset test | no | boolean | | `clear` | empty | yes | void |
- Why might list.removeAll(otherList) be unexpectedly slow?removeAll calls otherList.contains() for each element of list. A List's contains() is O(n), making it O(n*m). Convert otherList to a HashSet to get O(1) contains and O(n) overall.
- What does the boolean returned by retainAll mean?It is true if the collection was modified (some elements removed), false if everything was already in the argument and nothing changed.
- Confusing removeAll (difference) with retainAll (intersection)
- Thinking containsAll mutates - it does not
- Ignoring the O(n*m) cost when the argument is a List
- Assuming bulk ops always succeed - they can throw UnsupportedOperationException on unmodifiable collections
- Calling addAll on a List a union (it appends, duplicates included)
context
- Collection (Java SE 27 & JDK 27)docs.oracle.com
- Set (Java SE 27 & JDK 27)docs.oracle.com
- AbstractCollection (Java SE 27 & JDK 27)docs.oracle.com