Internal Working of HashSet in Java
Dattatray Bharde
open to work | Java Developer | Java | Specializing in JDBC, Hibernate, Spring Boot | Building Scalable Microservices with Springboot | Git | Redis | Docker
What is HashSet?
Internal Working of HashSet
How add() Works Internally?
Internal Code
Performance & Time Complexity
Handling Collisions in HashSet
Common Mistakes & Pitfalls
? Overriding equals() without hashCode()
Real-World Use Cases of HashSet
? Removing duplicates from a list – Fast, unordered duplicate removal for large datasets. ? Fast lookups in caching – O(1) time complexity for checking existence. ? Preventing duplicate usernames in registration – Ensures uniqueness with fast O(1) lookups.
Final Thoughts
Example: Collision in HashSet
import java.util.HashSet;
import java.util.Objects;
class Employee {
String name;
int id;
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public int hashCode() {
领英推荐
return id % 10; // Forces collision when id has the same last digit
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee employee = (Employee) obj;
return id == employee.id && Objects.equals(name, employee.name);
}
@Override
public String toString() {
return "Employee{name='" + name + "', id=" + id + "}";
}
}
public class HashSetCollisionExample {
public static void main(String[] args) {
HashSet<Employee> employees = new HashSet<>();
Employee e1 = new Employee("Alice", 101);
Employee e2 = new Employee("Bob", 111); // Same hash (101 % 10 == 111 % 10)
Employee e3 = new Employee("Charlie", 121); // Same hash
employees.add(e1);
employees.add(e2);
employees.add(e3);
System.out.println("Employees in HashSet:");
for (Employee e : employees) {
System.out.println(e);
}
// Checking if an object with the same values exists
System.out.println("Contains Alice (101)? " + employees.contains(new Employee("Alice", 101)));
}
}