Java ProgramsCollectionsHashSet Example

HashSet Example in Java

beginner·  Collections  ·  Set

Problem

A HashSet stores each distinct element at most once — adding a value that's already present has no effect, and the set never guarantees any particular iteration order.

Add several elements to a HashSet, including one duplicate, and confirm the duplicate didn't create a second entry.

Input
add("Apple"), add("Banana"), add("Cherry"), add("Apple")
Output
Size: 3 Contains Banana: true Contains Mango: false

Java Program

Java
import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> fruits = new HashSet<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); fruits.add("Apple"); // already present — silently ignored System.out.println("Size: " + fruits.size()); System.out.println("Contains Banana: " + fruits.contains("Banana")); System.out.println("Contains Mango: " + fruits.contains("Mango")); } }

Output

Size: 3 Contains Banana: true Contains Mango: false

Core Logic

Adding the same value twice only ever results in one entry, since add() checks for an existing equal element before inserting — checking the final size confirms the duplicate never took effect.

How It Works
  1. 1add("Apple"), add("Banana"), add("Cherry") insert three distinct fruits.
  2. 2add("Apple") again does nothing — HashSet's add() uses equals()/hashCode() to detect the value is already present, and returns false without changing the set.
  3. 3size() reports 3, not 4, confirming the second Apple never became a separate entry.
  4. 4contains("Banana") and contains("Mango") check membership directly, without needing to iterate the set at all.
Even though four add() calls were made, the set only ever holds three elements — the repeated Apple simply had no effect.
💡

Key Point: HashSet gives no guarantee about iteration order — unlike a List, there's no reliable way to predict what order a for-each loop over this set would print in, which is why this example checks size() and contains() instead of printing every element.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

Why: add() and contains() are backed by the same hash table a HashMap uses internally, giving average-case constant-time lookups, while the set holds up to n distinct elements.

Key Concepts

HashSetadd()contains()uniqueness

Related Programs