覆盖hashCode()和equals()以在hashMap中存储对象 - 而不是替换第一个条目

时间:2016-06-08 05:11:13

标签: java hashmap

HashMap代码 -

    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 - 覆盖等于&amp; hashCode函数

    @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();
    }

它不会替换hashmap中的条目。在system.out我得到“Dao”但期待“汤普森”。

0 个答案:

没有答案