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

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
+4
source share
4 answers

equals(Object o) this == o. , , , . , Employee e3 = new Employee (10, "Samad", 30), e1, , hashCode() equals(Object) .

+5

, equals(), hashCode(). , , . , , , , .

, hashCode, equals().

equals() hashCode() Object .

+1

equals true ( hashCode), , Employee. , e1, HashMap, containsKey(e1) true. Employee, e3 , e1, containsKey(e3) false, equals hashCode Employee.

+1

Object hashCode equals, HashMap. , , , .

, equals, hashCode, , "", hashCode ( , equals , hashCode ).

+1

Source: https://habr.com/ru/post/1527766/


All Articles