Skip to content
CampusEduX

Collections Framework · Lesson 78 of 150

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 min read

01What 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.

02Why 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.

03Real-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.

04Syntax

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

05Example 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

06Key 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.