Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

HashSet.add(E) — add an element to a set

`HashSet.add(E)` returns `true` when it inserts a new element and `false` when the set already contains an equal element.

Version: Java SE 21

Syntax

public boolean add(E e)

In Java SE 21, HashSet.add(E) is an instance method of java.util.HashSet<E>. It takes one element e of the set's element type E, such as String in HashSet<String>.

If the set has no element e2 for which Objects.equals(e, e2) returns true, the method inserts e, increases the size by one, and returns true. Otherwise it returns false and leaves the set unchanged: it does not replace the existing element. HashSet permits null, so the first addition of null returns true; another returns false while null remains in the set.

For your own classes, keep equals and hashCode consistent: equal objects must have the same hash code, but a matching hash code does not imply equality. Do not change the data used by either method while the object is in the set. HashSet guarantees no iteration order, including insertion order.

Use if (tags.add(tag)) to run code only when an element was inserted, without calling contains first. Not every Set behaves this way: a set created by Set.of(...) is unmodifiable, and calling add on it throws UnsupportedOperationException.

Examples

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> tags = new HashSet<>();

        System.out.println(tags.add("java"));
        System.out.println(tags.add(new String("java")));
        System.out.println(tags.add(null));
        System.out.println(tags.add(null));
        System.out.println(tags.size());
    }
}

Result

true
false
true
false
2

`new String("java")` deliberately creates a different object with the same text. The second call returns `false` because the strings are equal, not because they are the same object. The final set has two elements: `"java"` and `null`.

Related lessons

  • Java · Lesson 55 · Basic · Version: 2

Sources