HashSet<E> · Java

addAll / retainAll / removeAll

Union, intersection and difference, in place.

boolean addAll(Collection<? extends E> c); boolean retainAll(Collection<?> c); boolean removeAll(Collection<?> c)

Complexity

ExpectedaddAll O(m); retainAll O(n) contains calls on c; removeAll depends on which side is smaller
Extra spaceO(1)

Assumes: For retainAll/removeAll, c.contains must be fast: pass a Set, not a List (a List makes it O(n·m)).

Each element costs one membership test or insertion on one side or the other.

Tested example

Set<Integer> a = new HashSet<>(List.of(1, 2, 3));
a.addAll(List.of(3, 4));      // union, in place
assert a.equals(Set.of(1, 2, 3, 4));
a.retainAll(Set.of(2, 4, 6)); // intersection, in place
assert a.equals(Set.of(2, 4));
a.removeAll(Set.of(4));       // difference, in place
assert a.equals(Set.of(2));
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/HashSetExamples.java

Parameters

c
Any collection.

Behaviour

Returns
Whether the set changed.
Errors and preconditions
NullPointerException if c is null.
Changes
Modifies this set.
Memory and invalidation
addAll may resize.