Using Class object as a key in HashMap in Java

We can use a Class object as a key in HashMap in we want to make a mutable class object as a key in the HashMap, then we have to make sure that the state change for the key object does not change the hashcode of the object.

  • This can be done by overriding the equals() and hashCode() method.
  • To contract between the hashCode() and equals() said that If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • I have created an Employee class with only two fields. I have overridden the hashcode and equals method such that it uses name and age to verify the uniqueness of Employee object.

hashCode() :- HashMap provides put(key, value) for storing and get(key) for retrieving values from a HashMap.

Syntax :-         public int hashCode()

equals() :- equals() is used to compare objects for equality. In the case of HashMap, the key object is used for comparison, also using equals().

Syntax :-         public boolean equals(Object obj)

					import java.util.HashMap;

class Employee {
	private String name;
	private int age;

	public Employee(String name, int age) { = name;
		this.age = age;

	public String toString() {
		return "Employee [name=" + name + ", age=" + age + "]";

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Employee other = (Employee) obj;
		if (age != other.age)
			return false;
		if (name == null) {
			if ( != null)
				return false;
		} else if (!name.equals(
			return false;
		return true;

public class ObjectKeyHashMap {
	public static void main(String[] args) {
		Employee emp1 = new Employee("Aman", 20);
		Employee emp2 = new Employee("Pankaj", 40);
		HashMap<Employee, String> hmap = new HashMap<Employee, String>();
		hmap.put(emp1, "india");
		hmap.put(emp2, "US");

Output :-
{Employee [name=Aman, age=20]=india, Employee [name=Pankaj, age=40]=US}