Question

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
Was it helpful?

Solution

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.

OTHER TIPS

The rule is not that you must override both equals() and hashCode(). Rule is that, if you override one, you must override the other. Also, make sure the key is immutable, else you won't find the key if it is modified after being added to the map.

Also an important point is that, you should use the same fields to calculate the hashCode that you're using in equals().

The default implementation of equals() and hashCode() in Object class already satisfies the contract of those methods.

Object's default equals method returns true (and the same hashCode) if it's the same object reference, and you didn't override them in Employee. You are supplying the same object reference, e1, as what's already in the HashMap, so it containsKey(e1) returns true. If you were to create a separate Employee object, e3, with the same attributes as e1, then containsKey(e3) would return false unless you override equals and hashCode properly in Employee.

The class Object already contains implementations for hashCode and equals, and these work fine in a HashMap. The behavior that you'll get, however, is comparing for the same object, not whether two different objects are equivalent.

The important rule is that if you do override equals, you need to override hashCode so that objects that are "equal" have the same hashCode (which means that the equals method needs to compare all of the fields that hashCode uses to build its value).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top