A collection that doesnβt allow duplicates.
Implements Collection, but ignores order (unless special types).
Common Implementations
Implementation | Features |
---|---|
HashSet | Unordered, allows 1 null, fastest |
LinkedHashSet | Maintains insertion order |
TreeSet | Sorted set (natural or custom order) |
Key Properties
- No duplicates.
- No index-based access (
get(index)
not available). - Fastest membership checks:
contains(...)
. - Uses
quals()
andhashCode()
to detect duplicates.
Example
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)
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
Feature | HashSet | LinkedHashSet | TreeSet |
---|---|---|---|
Ordering | β | β Insertion order | β Sorted |
Performance | β Fastest | Slightly slower | β Slower |
Nulls | β 1 null allowed | β 1 null allowed | β No nulls allowed |
Under the hood | Hash table | Hash table + linked list | Red-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