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
| Expected | addAll O(m); retainAll O(n) contains calls on c; removeAll depends on which side is smaller |
|---|---|
| Extra space | O(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));
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.