Can we use a custom class as a key in a HashMap?

Yes, a class can be used as a key in a HashMap. In fact, custom class objects are frequently used as keys in real-world applications. However, to ensure correct behavior, the class should properly override the equals() and hashCode() methods. These methods help HashMap identify, store, and retrieve keys efficiently.

Key Points

How HashMap Uses a Custom Class Key

When a custom object is used as a key

1. HashMap calls hashCode() to find the bucket.

2. HashMap calls equals() to check whether the key already exists.

3. If a matching key is found, the value is updated.

4. Otherwise, a new key-value pair is added.

Example

Suppose an Employee object is used as a key.

Employee(101, "John")
Employee(102, "David")

Each employee object can act as a unique key.

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

class Employee {

    private int id;

    Employee(int id) {
        this.id = id;
    }

    @Override
    public int hashCode() {

        return Objects.hash(id);
    }

    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Employee)) {
            return false;
        }

        Employee emp = (Employee) obj;

        return this.id == emp.id;
    }
}

public class Demo {

    public static void main(String[] args) {

        Map<Employee, String> map =
                new HashMap<>();

        map.put(new Employee(101), "John");

        System.out.println(
                map.get(new Employee(101)));
    }
}

Output

John

Why Override hashCode() and equals()?

Without overriding them

Example Problem

Employee emp1 = new Employee(101);

Employee emp2 = new Employee(101);

Without proper equals() and hashCode()

emp1 and emp2 are treated as different keys.

Result

Unexpected behavior during retrieval and comparison.

Best Practices for HashMap Keys

Good Key Examples

Real-World Use Cases

Interview Tip

A concise interview answer is

Yes, a custom class can be used as a key in a HashMap. To ensure correct storage and retrieval, the class should properly override hashCode() and equals(). HashMap uses hashCode() to locate the bucket and equals() to identify the correct key within that bucket.

Last updated: 11 November 2026

Previous question: What changed in HashMap in Java 8?

Next question: What is ConcurrentHashMap in Java?

More Core Java - Level II interview questions

All Core Java - Level II questions