HashSet – In Java
import java.util.HashSet;
public class Program3 {
public static void main(String[] args) {
HashSet<String> country = new HashSet<String>();
country.add("India");
country.add("USA");
country.add("China");
country.add("Russia");
System.out.println(country);
}
}
Output –
[USA, China, India, Russia]
Note: The order may change every time you run the program. That’s because HashSet does not maintain insertion order.
🔍 What is a HashSet?
HashSetis a collection of unique elements — duplicates are not allowed.It is part of Java’s Collection Framework.
It is unordered — the elements may not appear in the order you added them.
💡 Key Features:
| Feature | Description |
|---|---|
| No Duplicates | Automatically ignores duplicate entries |
| Fast Lookup | Uses hashing for quick access |
| No Order Guarantee | Elements can appear in any order |
❗ Example: Adding Duplicate
🔁 Looping Through a HashSet:
📦 When to Use HashSet:
When you need to store unique values.
When you don’t care about the order.
Useful for things like tags, sets of IDs, or filtering duplicates.