We can use a Class object as a key in HashMap in Java.here 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) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
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 (other.name != null)
return false;
} else if (!name.equals(other.name))
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 hmap = new HashMap();
hmap.put(emp1, "india");
hmap.put(emp2, "US");
System.out.println(hmap);
}
}
Output :-
{Employee [name=Aman, age=20]=india, Employee [name=Pankaj, age=40]=US}