What are the operations of the set ADT, and how do addAll, retainAll and removeAll relate to union, intersection and difference?
add, remove, contains and iterator work on single elements. addAll(T) turns S into S ∪ T, retainAll(T) into S ∩ T, and removeAll(T) into S − T.
Element operations:
add(e): insert e, unless it is already there.remove(e): delete e, if present.contains(e): is e in S?iterator(): visit all elements.
Whole-set operations, each of which changes S in place:
| Method | Keeps in S | Set notation |
|---|---|---|
addAll(T) |
everything in S or T | S ∪ T |
retainAll(T) |
only what is also in T | S ∩ T |
removeAll(T) |
only what is not in T | S − T |
Merging two playlists is a union: a song that is on both lists should appear in the result only once.
Example with S = {1, 2, 3} and T = {2, 3, 4}: addAll gives {1, 2, 3, 4}, retainAll gives {2, 3}, removeAll gives {1}.
With a hash-based set, each of these is one contains check per element, so the cost is linear in the size of the sets involved. Python writes the same three as S | T, S & T and S - T (new sets) or |=, &=, -= (in place).