As I know, if we want to use the object as a key in HashMap, we need to implement methods hashCodeand equals(in this class) for the correct operation. But in the code below, I used the object as a key, but did not implement the above two methods in this class Employee, and it works fine.
Could you explain why it works without hashCodeand equals?
public class Employee1 {
Integer Roll;
String Name;
int age;
Employee1(int roll,String name,int Age)
{
this.Roll =roll;
this.Name= name;
this.age =Age;
}
}
public static void main(String ar[]) {
Map<Employee, Integer> ObjectAsKeyMap = new HashMap<Employee, Integer>();
Employee e1 = new Employee(10, "Samad", 30);
Employee e2 = new Employee(50, "Sahar", 20);
ObjectAsKeyMap.put(e1, 10);
ObjectAsKeyMap.put(e2, 20);
if (ObjectAsKeyMap.containsKey(e1))
System.out.println("this Object is already present in HashMap Value="+ObjectAsKeyMap.get(e1));
}
Output:
this Object is already present in HashMap Value=10
source
share