Ideally, as per the definition, HashMap does not allow duplicate keys; but I couldn't understand the following logic.
I have defined an Employee class and overridden the equals and hashcode methods.
public class Employee {
private String empID;
public int hashCode() {
int result = 17;
result = 37 * result + empID.hashCode();
return result;
}
public boolean equals(Object object) {
boolean result = false;
if (object instanceof Employee) {
Employee employee = (Employee) object;
result = (this.empID.equalsIgnoreCase(employee.getEmpID()));
}
return result;
}
}
Employee e1 = new Employee("1");
Employee e2 = new Employee("2");
Map<Employee, String> empMap = new HashMap<Employee, String>();
empMap.put(e1, "Emp1");
empMap.put(e2, "Emp2");
Set<Employee> keys = empMap.keySet();
for (Employee e: keys)
{
e.setEmpID("1");
}
for (Employee e: keys)
{
System.out.println(e.getEmpID());
System.out.println(e.hashCode());
}
System.out.println(empMap.get(new Employee("1")) );
I am always getting the value Emp1. How to get the value Emp2?
equalsignores case, but yourhashCodedoesn't.