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 ?