Question

I have an Employee class and I override the hashCode() method and not the equals() method

public class Employee {
public int id;
public String name;
public Employee (int id, String name) {
    this.id = id;
    this.name = name;
}
@Override
public int hashCode() {
    return name.hashCode();
}
}

Now the client adds 3 data where the hashCode() will be the same.

public class EmployeeTest {
public static void main(String...args) {
    Employee emp1 = new Employee(11, "Arunan");
    Employee emp2 = new Employee(22, "Arunan");
    Employee emp3 = new Employee(33, "Arunan");

    HashMap<Employee,Employee> map = new HashMap<>();
    map.put(emp1, emp1);
    map.put(emp2, emp2);
    map.put(emp3, emp3);

    Employee emp = map.get(emp3);
    System.out.println(emp.id);
}
}

Now as per my understanding, the above 3 objects will end up in same bucket in hashmap. Since equals() is not implemented, its hard for the HashMap to identify the particular object. But in the above program, i get the emp3 object and it is correctly fetching the emp3 object. How the hashmap works ?

Was it helpful?

Solution

You are right about them ending up in the same bucket.

In the absence of an overridden equals method, the JVM will just compare the object references for equality.

In your case you are passing the same object to map.get() as you put in the map, so the references will be equal and so it matches the object.

Try creating:

Employee emp3CantFindMe = new Employee(33, "Arunan")

You'll find trying to retrieve that from the map will result in null even though it seems to be the "same" as emp3.

OTHER TIPS

HashMap first uses the hashCode to find possible candidates and after that uses equals to find the actual object you are looking for. Even good hashCode implementations necessarily have collisions that cannot be considered negligable. So having to objects with same hashCode which are not equal may be bad performance wise if these collisions happen to often, but it does not break semantics. The other way around (having equal objects with different hashCodes) does break semantics.

Default implementation of equals() returns true if both objects are actually the same object. And in your case you use the same object (emp3) you put into the hashmap to query the hashmap. That is why it works.

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