A collection that doesn’t allow duplicates.
Implements Collection, but ignores order (unless special types).

Common Implementations

ImplementationFeatures
HashSetUnordered, allows 1 null, fastest
LinkedHashSetMaintains insertion order
TreeSetSorted set (natural or custom order)

Key Properties

  • No duplicates.
  • No index-based access (get(index) not available).
  • Fastest membership checks: contains(...).
  • Uses quals()and hashCode()to detect duplicates.

Example

HashSet
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Java"); // Duplicate is ignored
set.add("Python");
 
System.out.println(set); // ["Java", "Python"] (order not guaranteed)
TreeSet
Set<Integer> numbers = new TreeSet<>();
numbers.add(3);
numbers.add(1);
numbers.add(2);
 
System.out.println(numbers); // [1, 2, 3] - sorted

Comparison

HashSet vs TreeSet vs LinkedHashSet

FeatureHashSetLinkedHashSetTreeSet
Orderingβœ—βœ… Insertion orderβœ… Sorted
Performanceβœ… FastestSlightly slowerβœ— Slower
Nullsβœ… 1 null allowedβœ… 1 null allowedβœ— No nulls allowed
Under the hoodHash tableHash table + linked listRed-black tree

Use Cases

  • HashSet: uniqueness, fast lookup (e.g. filter duplicates).
  • LinkedHashSet: uniqueness + predictable order (e.g. caching).
  • TreeSet: sorted data (e.g. leaderboards, autocomplete).

Tip

Be ready to explain:

  • explain how Set avoids duplicates,
  • talk about hashCode() + equals(),
  • compare all 3 Set types and when to use each.

Parent: _Collections