Set.add()
Adds an element if it is not in the set yet.
Available since: Java 1.2
Syntax
boolean add(E e)Parameters
| Parameter | Type | Description |
|---|---|---|
| e | E | The element to add. |
Return value
boolean`true` if the element was absent and has been added; `false` if it was already there.
Examples
The result of add() reports a duplicate:
void main() {
Set<String> seen = new HashSet<>();
for (String email : List.of("a@x.com", "b@x.com", "a@x.com")) {
if (!seen.add(email)) {
IO.println("Duplicate: " + email);
}
}
}Output:
Duplicate: a@x.comNotes
A separate contains() check before add() is not needed — the return value already tells whether the element was there. Unmodifiable sets (Set.of()) throw UnsupportedOperationException.
See also
- Set.contains() — Checks whether a set contains an element.
- Set.remove() — Removes an element from a set.
- Set.addAll() — Merges a set with another collection (union).
- HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
Related recipes
In the tutorial
- Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.