HashSet<E> · Java
add
Adds an element if absent.
public boolean add(E e)
Complexity
| Expected | O(1) |
|---|---|
| Amortized | O(1) |
| Worst case | O(n) |
| Extra space | O(1) amortized |
Assumes: Good hash distribution.
A HashMap.put with a dummy value.
Tested example
Set<Integer> seen = new HashSet<>();
assert seen.add(4);
assert !seen.add(4); // already present: false, set unchanged
assert seen.size() == 1;
Parameters
- e
- The element (null allowed once).
Behaviour
- Returns
- true if the set changed.
- Errors and preconditions
- None.
- Changes
- At most one new element; may resize.
- Memory and invalidation
- May resize the backing table.