1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Hashset Basics
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Hashset Basics

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

HashSet

Overview

A HashSet is a collection that stores only unique elements. If you try to add a duplicate, the add() method simply returns false and the set remains unchanged. It is the go-to data structure whenever your primary requirement is "does this item already exist?" or "give me a deduplicated list".

Internally, HashSet is literally implemented as a HashMap where the element you add becomes the Key, and a static dummy Object is always used as the Value. This means HashSet inherits all the performance characteristics of HashMap: O(1) amortized time for add(), remove(), and contains().

Like HashMap, a HashSet makes no guarantees about the order of its elements. If you need a sorted unique collection, use TreeSet. If you need insertion-order uniqueness, use LinkedHashSet.

Syntax

Unique Elements and Set Operations
java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> visitedPages = new HashSet<>();
        
        // 1. Adding Elements (Duplicates are silently ignored)
        visitedPages.add("/home");
        visitedPages.add("/products");
        visitedPages.add("/home");   // Duplicate — ignored!
        visitedPages.add("/contact");
        
        System.out.println("Visited: " + visitedPages.size()); // 3, not 4!
        
        // 2. O(1) Membership Check
        if (!visitedPages.contains("/checkout")) {
            System.out.println("First visit to checkout!");
            visitedPages.add("/checkout");
        }
        
        // 3. Set Math Operations
        Set<Integer> setA = new HashSet<>(Set.of(1, 2, 3, 4, 5));
        Set<Integer> setB = new HashSet<>(Set.of(3, 4, 5, 6, 7));
        
        // Union (All elements from both sets)
        Set<Integer> union = new HashSet<>(setA);
        union.addAll(setB); // {1, 2, 3, 4, 5, 6, 7}
        
        // Intersection (Only common elements)
        Set<Integer> intersection = new HashSet<>(setA);
        intersection.retainAll(setB); // {3, 4, 5}
    }
}

Common Pitfalls

  • Assuming HashSet will maintain insertion order. Like HashMap, HashSet provides no ordering guarantee. If you need predictable iteration order, use LinkedHashSet (preserves insertion order) or TreeSet (natural sort order).
  • Storing mutable objects without overriding hashCode() and equals(). HashSet uses hashCode() to find the bucket and equals() to confirm a duplicate. If your custom class doesn't override both methods consistently, HashSet may store 'duplicate' objects because it compares memory addresses instead of logical equality.
  • Using a HashSet to check for duplicates on a List of custom objects without overriding hashCode(). This is an extremely common bug. Even if two objects represent the same real-world entity, without proper equals() and hashCode() overrides, the set treats them as different objects.

Interview Questions

How does HashSet internally guarantee uniqueness?

HashSet is backed by a HashMap. When you call set.add(element), it internally calls map.put(element, DUMMY_OBJECT). Because HashMap keys must be unique, the set's elements are inherently unique. The add() method returns true if the element was new, and false if it was a duplicate (the map already had that key).

Why must you override BOTH hashCode() and equals() when using a custom object in a HashSet?

Java's HashSet (and HashMap) first uses hashCode() to find the correct bucket. If two objects share a bucket (same hash), it then uses equals() to determine if they are truly the same element. If you override only equals() but not hashCode(), two logically equal objects may hash to different buckets and both get stored — completely breaking the uniqueness guarantee.

Real-World Example

Tracking unique website visitors for analytics in real time. For every incoming request, you check whether the user's session ID is in the HashSet. The O(1) lookup means this check adds virtually zero latency to every single page view, even at millions of requests per second.

example
java
Set<String> uniqueVisitors = new HashSet<>();

public void onRequest(HttpRequest req) {
    String sessionId = req.getHeader("Session-ID");
    
    // O(1) uniqueness check
    boolean isNewVisitor = uniqueVisitors.add(sessionId);
    
    if (isNewVisitor) {
        analytics.recordUniqueVisit();
    }
}

Check Your Knowledge

Test your understanding of HashSet with these quick questions.

Question 1

What does `set.add(element)` return if the element already exists in the HashSet?

Question 2

Which HashSet variant maintains insertion order?

Question 3

A HashSet contains `Point(1,1)` and you try to add a new `Point(1,1)`. What happens if `Point` does NOT override `hashCode()`?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

HashSet

Overview

A HashSet is a collection that stores only unique elements. If you try to add a duplicate, the add() method simply returns false and the set remains unchanged. It is the go-to data structure whenever your primary requirement is "does this item already exist?" or "give me a deduplicated list".

Internally, HashSet is literally implemented as a HashMap where the element you add becomes the Key, and a static dummy Object is always used as the Value. This means HashSet inherits all the performance characteristics of HashMap: O(1) amortized time for add(), remove(), and contains().

Like HashMap, a HashSet makes no guarantees about the order of its elements. If you need a sorted unique collection, use TreeSet. If you need insertion-order uniqueness, use LinkedHashSet.

Syntax

Unique Elements and Set Operations
java
import java.util.HashSet;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<String> visitedPages = new HashSet<>();
        
        // 1. Adding Elements (Duplicates are silently ignored)
        visitedPages.add("/home");
        visitedPages.add("/products");
        visitedPages.add("/home");   // Duplicate — ignored!
        visitedPages.add("/contact");
        
        System.out.println("Visited: " + visitedPages.size()); // 3, not 4!
        
        // 2. O(1) Membership Check
        if (!visitedPages.contains("/checkout")) {
            System.out.println("First visit to checkout!");
            visitedPages.add("/checkout");
        }
        
        // 3. Set Math Operations
        Set<Integer> setA = new HashSet<>(Set.of(1, 2, 3, 4, 5));
        Set<Integer> setB = new HashSet<>(Set.of(3, 4, 5, 6, 7));
        
        // Union (All elements from both sets)
        Set<Integer> union = new HashSet<>(setA);
        union.addAll(setB); // {1, 2, 3, 4, 5, 6, 7}
        
        // Intersection (Only common elements)
        Set<Integer> intersection = new HashSet<>(setA);
        intersection.retainAll(setB); // {3, 4, 5}
    }
}

Common Pitfalls

  • Assuming HashSet will maintain insertion order. Like HashMap, HashSet provides no ordering guarantee. If you need predictable iteration order, use LinkedHashSet (preserves insertion order) or TreeSet (natural sort order).
  • Storing mutable objects without overriding hashCode() and equals(). HashSet uses hashCode() to find the bucket and equals() to confirm a duplicate. If your custom class doesn't override both methods consistently, HashSet may store 'duplicate' objects because it compares memory addresses instead of logical equality.
  • Using a HashSet to check for duplicates on a List of custom objects without overriding hashCode(). This is an extremely common bug. Even if two objects represent the same real-world entity, without proper equals() and hashCode() overrides, the set treats them as different objects.

Interview Questions

How does HashSet internally guarantee uniqueness?

HashSet is backed by a HashMap. When you call set.add(element), it internally calls map.put(element, DUMMY_OBJECT). Because HashMap keys must be unique, the set's elements are inherently unique. The add() method returns true if the element was new, and false if it was a duplicate (the map already had that key).

Why must you override BOTH hashCode() and equals() when using a custom object in a HashSet?

Java's HashSet (and HashMap) first uses hashCode() to find the correct bucket. If two objects share a bucket (same hash), it then uses equals() to determine if they are truly the same element. If you override only equals() but not hashCode(), two logically equal objects may hash to different buckets and both get stored — completely breaking the uniqueness guarantee.

Real-World Example

Tracking unique website visitors for analytics in real time. For every incoming request, you check whether the user's session ID is in the HashSet. The O(1) lookup means this check adds virtually zero latency to every single page view, even at millions of requests per second.

example
java
Set<String> uniqueVisitors = new HashSet<>();

public void onRequest(HttpRequest req) {
    String sessionId = req.getHeader("Session-ID");
    
    // O(1) uniqueness check
    boolean isNewVisitor = uniqueVisitors.add(sessionId);
    
    if (isNewVisitor) {
        analytics.recordUniqueVisit();
    }
}

Check Your Knowledge

Test your understanding of HashSet with these quick questions.

Question 1

What does `set.add(element)` return if the element already exists in the HashSet?

Question 2

Which HashSet variant maintains insertion order?

Question 3

A HashSet contains `Point(1,1)` and you try to add a new `Point(1,1)`. What happens if `Point` does NOT override `hashCode()`?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A