CKTIS / Java
java.util.Set — a collection without duplicates
Set<E> describes a collection of unique elements. Learn how to add, check, remove, and count elements, and distinguish the Set interface from the HashSet implementation.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
Set<E> values = new HashSet<>();
boolean added = values.add(element);
int count = values.size();
boolean present = values.contains(element);
boolean removed = values.remove(element);java.util.Set<E> is a collection interface without duplicates; E denotes the element type. The set contract defines duplicates through equals, not object identity. Set guarantees neither iteration order nor indexed access.
Set.add(E) returns true when a new element is added; for a duplicate, it returns false and leaves the set unchanged. Set.size() returns the element count as an int (capped at Integer.MAX_VALUE). Set.contains(Object) tests membership. If Set.remove(Object) completes normally, it returns true if it removed the element and false if the element was absent.
HashSet is a modifiable implementation: it permits null, guarantees no iteration order, and is not synchronized. Support for null depends on the implementation. Mutating operations are optional in the interface and may throw UnsupportedOperationException even when the element is absent. For example, Set.of("java").remove("missing") throws that exception instead of returning false.
Do not change fields affecting equals while an object belongs to a set: the set's behavior is then unspecified. The example uses String and prints only operation results, so it does not depend on iteration order.
Examples
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> tags = new HashSet<>();
System.out.println(tags.add("java"));
System.out.println(tags.add("java"));
System.out.println(tags.size());
System.out.println(tags.contains("java"));
System.out.println(tags.remove("java"));
System.out.println(tags.remove("java"));
System.out.println(tags.size());
}
}Result
true false 1 true true false 0
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.