As I know, if we want to use object as key in HashMap, we need to implement hashCode and equals methods (on that class) to work properly. But in the below code I used object as key but didn't implement above two methods on that Employee class, and it's working fine.
Could you please clarify why it's working without hashCode and 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
The default implementation of equals(Object o) is this == o. Since you're using an object as a key, and then using the same instance to query the map, it would work.
However, if you had created Employee e3 = new Employee (10, "Samad", 30), even though logically it should be equal to e1, it would not have worked, since you did not implement hashCode() and equals(Object) as required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With