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: • Custom class objects can be used as HashMap keys. • hashCode() determines the bucket where the key is stored. • equals() is used to compare keys within the same bucket. • Both methods should be overridden consistently. • Improper implementation can lead to duplicate keys or failed lookups.
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.
Code Example:
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:
• Two logically identical objects may be treated as different keys. • HashMap may fail to find an existing entry. • Duplicate keys can be stored unintentionally.
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
• Make key objects immutable whenever possible. • Override both equals() and hashCode(). • Use fields that uniquely identify the object. • Avoid modifying key fields after insertion.
Good Key Examples:
• String • Integer • Long • UUID • Immutable custom classes
Real-World Use Cases:
• Employee object as a key for employee details. • Product object as a key for inventory data. • Customer object as a key for account information.
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."