Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of hashCode and equals of a custom object to use as a key in HashMap

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
like image 768
Skabdus Avatar asked Feb 14 '23 18:02

Skabdus


1 Answers

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.

like image 102
Mureinik Avatar answered Feb 23 '23 00:02

Mureinik