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, unordered
  • LinkedHashSet β€” O(1) operations, maintains insertion order
  • TreeSet β€” O(log n) operations, keeps elements sorted
  • EnumSet β€” bitset-backed, fastest for enum types
  • CopyOnWriteArraySet β€” 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);