DIGITAL GURU
Java DSA Portfolio

HashMap, HashSet & Custom Hashing

Master key-value lookup, hash functions, hashCode(), equals(), and O(1) operations.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide

Formal Definition & Classification Types

Definition: Hashing is a technique that maps large keys into small fixed-size integer indices using a mathematical Hash Function, enabling $O(1)$ constant time data insertion and retrieval inside a Hash Table.

Types of Hash-Based Data Structures:

  • Hash Table / HashMap: Stores associative Key-Value pairs with unique keys (e.g., Java `HashMap` or C++ `std::unordered_map`).
  • HashSet: Stores a collection of unique elements with no duplicates (e.g., Java `HashSet` or C++ `std::unordered_set`).
  • LinkedHashMap / LinkedHashSet: Hash table maintaining insertion-order of elements via doubly linked list.

Real-World Analogy

A HashMap is like a mail room with 1,000 numbered mailboxes—a hash function converts a recipient's name into a specific mailbox number for instant access.

Hash Table Architecture

Hash tables compute an index via `hash(key) % capacity`. Provides $O(1)$ average time complexity for `get`, `put`, and `remove` operations.

Production Code Example:

CustomKeyDemo.java
import java.util.Objects;
public class CustomKeyDemo {
    private int id;
    private String name;
    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof CustomKeyDemo)) return false;
        CustomKeyDemo that = (CustomKeyDemo) o;
        return id == that.id && Objects.equals(name, that.name);
    }
    @Override public int hashCode() { return Objects.hash(id, name); }
}

Key Complexity & Algorithmic Takeaways:

When implementing HashMap, HashSet & Custom Hashing in coding interviews and production applications, keep these core guidelines in mind:

  • Time Complexity Analysis: Always evaluate best-case, average-case, and worst-case time complexities ($O(1)$, $O(\log n)$, $O(n)$, $O(n \log n)$, $O(n^2)$).
  • Space Complexity & Memory Bounds: Account for auxiliary memory usage, call stack frame recursion overhead, and heap allocations.
  • Edge Cases & Validation: Test empty inputs, null pointers, single-element collections, duplicate values, and integer overflow bounds.
  • Optimal vs Naive Solutions: Start with a clear brute-force solution, then optimize using techniques like Hashing, Two Pointers, Windowing, or Dynamic Programming.

Summary Takeaway:

Mastering HashMap, HashSet & Custom Hashing provides the foundational problem-solving skills needed to pass technical coding interviews at top tech companies and write ultra-performant software systems.

Mandatory Contract

If two objects are equal according to `equals()`, they MUST return the exact same `hashCode()`!