HashSet: Unique Elements with Hashing
What you'll learn: How HashSet enforces uniqueness and achieves near-instant lookups using hash-based storage.
What Is a HashSet?
A HashSet is a collection that stores unique elements only—no duplicates allowed. Under the hood, it uses hashing to organize elements into "buckets," which makes adding, removing, and checking for existence extremely fast.
Think of a HashSet like a giant filing cabinet where each drawer is labeled with a number (the hash code). When you add an item, Java calculates which drawer it belongs in, opens that drawer instantly, and checks if it's already there. No need to search through every drawer!
Key Characteristics
Constant-Time Operations: HashSet provides O(1) average-time complexity for:
add(element)– adds an element if it's not already presentremove(element)– removes the elementcontains(element)– checks if the element exists
No Duplicates: If you try to add an element that's already in the set, HashSet simply ignores it. The add() method returns false to indicate the element wasn't added.
HashSet<String> cities = new HashSet<>();
cities.add("Tokyo");
cities.add("Paris");
cities.add("Tokyo"); // Duplicate! Won't be added
System.out.println(cities.contains("Paris")); // true, nearly instant
System.out.println(cities.size()); // 2, not 3
No Ordering Guarantee
Unlike ArrayList, HashSet doesn't maintain any particular order. Elements are organized by their hash codes, not insertion order or natural sorting.
Key Takeaway: HashSet uses hashing to provide constant-time add, remove, and contains operations while automatically preventing duplicates—ideal when you need fast lookups and uniqueness matters more than order.