Topic 29 of 78
HashSet
Overview
A `HashSet` is a collection that completely prevents duplicate values. If you try to add "Apple" five times, it will only store it once. Furthermore, it has no concept of order or indexing (there is no `get(0)`). Under the hood, a HashSet is literally just a HashMap where the 'Values' are ignored, and your data is stored as the 'Keys'. This gives HashSet the same blazing fast O(1) lookup speed as HashMap.
Syntax
Use HashSet whenever you need to maintain a unique list of items, or when you need to repeatedly check if an item exists in a massive list.
HashSet
java
Set<String> uniqueEmails = new HashSet<>();
// 1. Adding elements
uniqueEmails.add("test@google.com");
boolean addedAgain = uniqueEmails.add("test@google.com");
// Returns false! Duplicates are silently ignored.
uniqueEmails.add("admin@google.com");
// 2. Extremely Fast Lookup O(1)
boolean exists = uniqueEmails.contains("test@google.com"); // true
// 3. Iterating (Order is completely random!)
for (String email : uniqueEmails) {
System.out.println(email);
}Common Pitfalls
- Assuming the elements will be printed out in the same order you inserted them. HashSet scrambles the order entirely based on Hash Codes.
- Just like HashMap, if you store Custom Objects in a HashSet, you MUST override `equals()` and `hashCode()`, otherwise it will treat identical objects as unique based on memory address.
Interview Tips
- A HashSet is literally just a HashMap under the hood where the values are dummy objects. It's used purely for maintaining unique keys.
Real-World Example
HashSets are perfect for detecting duplicates or visited nodes in algorithms.
example
java
public class RegistrationService {
// Keep a set of taken usernames in memory for instant validation
private Set<String> takenUsernames = new HashSet<>();
public boolean registerUser(String username) {
// .add() returns false if the username already exists!
if (!takenUsernames.add(username)) {
throw new Exception("Username already taken!");
}
saveToDb(username);
return true;
}
}