0

HashMap code -

    public class HashMapTest {

    public static void main(String[] args) {

    Employee e1 = new Employee("1", "Bob", "Dao");
    Employee e2 = new Employee("1", "Sam", "Thompson");

    Map<Employee, Employee> map = new HashMap<Employee, Employee>();
    map.put(e1, e1);
    map.put(e2, e2);

    Set<Employee> set = map.keySet();

    for(Employee emp : set)
    {
        System.out.println("Hash Map - Set is : "+emp.getEmpLastName());
    }
    }
    }

Employee.java - overrided equals & hashCode function

    @Override
    public boolean equals(Object obj) {
    if(obj==null)
        return false;
    Employee e = (Employee)obj;
    if(this.employeeId==e.employeeId)
        return true;
    return false;
    }

    @Override
    public int hashCode() {
    return 12 + employeeId.hashCode();
    }

It's not replacing entry in hashmap. In system.out am getting "Dao" but expecting "Thompson".

Ravi
  • 1
  • 1
  • 1
    You are only using `employeeId` in the `equals` and `hashCode`. I note your constructor takes three arguments. Which one is `employeeId`? What are the other ones? If `employeeId` isn't a primitive type, comparing the field with `==` isn't correct. – Elliott Frisch Jun 08 '16 at 05:14
  • You're comparing the employeeId fields using the `==` operator. Since employeeId is a string, you should compare using the `equals` method. See the suggested duplicate. – Erwin Bolwidt Jun 08 '16 at 05:16
  • Although in general strings should be compared with `equals`, in this particular case using `==` is not the problem because string literals are being interned. (I'm assuming the constructor of `Employee` doesn't do something like `this.employeeId = new String(employeeId);`) – Hoopje Jun 08 '16 at 05:35
  • 1
    The issue is not with "==" operator. The definition of V put(K key, V value) mentions that " If the map previously contained a mapping for the key, the old value is replaced by the specified value." ,which means the "old value" is replaced and not the "key" itself.In this case also,the key is same but the value has changed.You are printing the value in key(keySet) and not the one in value.If you dont want to just check the key value,use entrySet() instead of keySet().Hope that is clear – S.B Jun 08 '16 at 05:58
  • Thanks S.B., I understood the problem. – Ravi Jun 08 '16 at 14:58

0 Answers0