Set

Basic Java
≈ 2 min read

A collection without duplicates

Set<E> stores unique elements. If you try to add a value that the set considers equal to an existing one, a second copy will not appear. This is useful for identifiers, tags, permissions, and any other data where a duplicate adds no new meaning.

Set<String> tags = new HashSet<>();

System.out.println(tags.add("java")); // true
System.out.println(tags.add("sql"));  // true
System.out.println(tags.add("java")); // false

System.out.println(tags.size());      // 2

The add() method returns true if the set changed, and false if the element was already present.

No index — membership instead

A Set has no position such as “element number 3.” The main question for a set is usually different: does it contain a particular value? Use contains() for that.

Set<String> permissions = Set.of("READ", "WRITE");

if (permissions.contains("WRITE")) {
    System.out.println("Can edit");
}

The factory method Set.of(...) creates a set that cannot be modified after creation. It also rejects duplicate elements at creation time.

Order depends on the implementation

The Set interface itself does not promise a particular traversal order. Some implementations do not preserve one at all, while others keep insertion order or maintain sorted order. So you should not rely on an accidental order that happened to appear when a set was printed once.

Uniqueness is determined by object equality, not by appearance. For custom classes, correct equals() and hashCode() implementations are especially important. Their connection becomes very practical when we study HashSet.