Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Set.add()

Adds an element if it is not in the set yet.

Available since: Java 1.2

Syntax

boolean add(E e)

Parameters

ParameterTypeDescription
eEThe 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.com

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.