Skip to content
C

HashSet

HashSet is the most commonly used implementation of the Set interface. It stores unique elements and does not guarantee any particular order when you iterate through them.


1. What is HashSet?

HashSet is the most commonly used implementation of the Set interface. It stores unique elements and does not guarantee any particular order when you iterate through them.

2. Why is it used?

HashSet is used when you need fast operations (adding, removing, checking existence) and don't care about maintaining any specific order of elements.

3. Real-Life Example

Think of tossing unique tokens into a large basket without arranging them in any particular order. You can still quickly check if a specific token is in the basket, even though there's no defined sequence.

4. Syntax

java
HashSet<DataType> setName = new HashSet<>();

5. Example Program

java
import java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { HashSet<Integer> numbers = new HashSet<>(); numbers.add(10); numbers.add(20); numbers.add(10); // duplicate, ignored System.out.println(numbers.size()); } }

Output:

2

6. Key Points to Remember

  • HashSet offers very fast add, remove, and search operations on average.
  • The iteration order of a HashSet is unpredictable and should never be relied upon.
  • HashSet internally uses a HashMap to store its elements.