HashSet Example in Java
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.
Java Program
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
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.
- 1
add("Apple"),add("Banana"),add("Cherry")insert three distinct fruits. - 2
add("Apple")again does nothing — HashSet'sadd()usesequals()/hashCode()to detect the value is already present, and returnsfalsewithout changing the set. - 3
size()reports3, not4, confirming the second Apple never became a separate entry. - 4
contains("Banana")andcontains("Mango")check membership directly, without needing to iterate the set at all.
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.
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.