Set
A Set is a collection that contains no duplicate elements. Adding an element that equals an existing one is a no-op. Use HashSet as the default.
Example
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("java"); // ignored β already present
tags.add("jvm");
tags.size(); // 2
tags.contains("java"); // true
Implementations
HashSetβ O(1) add/remove/contains, unorderedLinkedHashSetβ O(1) operations, maintains insertion orderTreeSetβ O(log n) operations, keeps elements sortedEnumSetβ bitset-backed, fastest for enum typesCopyOnWriteArraySetβ thread-safe, good for read-heavy workloads
equals + hashCode contract
A Set relies on equals and hashCode to detect duplicates. If you put custom objects in a HashSet, you must override both methods consistently, otherwise duplicates will slip in.
Immutable set (Java 9+)
Set<Integer> primes = Set.of(2, 3, 5, 7, 11);