← Back to Chapters

HashSet in Java

? HashSet in Java

? Quick Overview

HashSet is a collection in Java that stores unique elements only. It does not maintain insertion order and allows fast operations using hashing.

? Key Concepts

  • Stores only unique values
  • Does not maintain order
  • Allows one null value
  • Based on hash table internally
  • Part of Java Collection Framework

? Syntax / Theory

HashSet belongs to the java.util package and implements the Set interface. It is commonly used when duplicates are not allowed.

? View Code Example
// Importing HashSet class
import java.util.HashSet;

public class Main {
public static void main(String[] args) {

// Creating a HashSet of Strings
HashSet cities = new HashSet<>();

// Adding elements to HashSet
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Chennai");
cities.add("Delhi");

// Printing HashSet
System.out.println(cities);
}
}

?️ Live Output / Explanation

The output will show city names without duplicates. Even though "Delhi" was added twice, it appears only once because HashSet does not allow duplicate values.

? Interactive Demo: Add to HashSet

Type a value and press Add. Try adding the same value twice to see how HashSet rejects duplicates!

Set is currently empty

? Tips & Best Practices

  • Use HashSet when order does not matter
  • Prefer HashSet for fast search operations
  • Do not rely on output order
  • Use LinkedHashSet if insertion order is required

? Try It Yourself

  • Create a HashSet of integers
  • Add duplicate numbers and observe the result
  • Check if an element exists using contains()
  • Remove an element from the HashSet