Java HashMap:如何用put() - Method替换自己的Key对象

时间:2016-09-29 13:59:13

标签: java object collections

假设我有Employee - 类Instant - 和Id - 属性:

public class Employee implements Comparable<Employee> {

    private Instant workEnd;
    private Integer id;
    private String name;

    public Instant getWorkEnd() {
        return workEnd;
    }

    public void setWorkEnd(Instant workEnd) {
        this.workEnd = workEnd;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Employee employee) {

        int workEndCompare = getWorkEnd().compareTo(employee.getWorkEnd());
        int idCompare = getId().compareTo(employee.getId());

        if (workEndCompare == 0) {
            return idCompare;
        } else {
            return workEndCompare;
        }
    }

    @Override
    public String toString() {
        return String.format("{Date: %s,Number: %d}", getWorkEnd(), getId());
    }
}

您可以看到每个Employee - 对象排序取决于workEndid

现在我想将这些Employee - 对象作为键放在HashMap中。但是如果属性Employeeput()相等,我希望HashMap用workend - 方法替换每个键 - id。这意味着我想要HashMap的正常行为,但使用自己的自定义对象作为Mapkeys。

我是如何管理的?通过实现equals方法?

我尝试了类似的东西,但它不起作用:

@Override
public boolean equals(Object obj) {
    if (obj instanceof Employee) {
        Employee employee = (Employee) obj;
        int workEndCompare = getWorkEnd().compareTo(employee.getWorkEnd());
        int idCompare = getId().compareTo(employee.getId());

        if ((idCompare + workEndCompare) == 0) {
            return true;
        } else {
            return false;
        }

    } else {
        return super.equals(obj);
    }
}

1 个答案:

答案 0 :(得分:2)

实现equals方法时,还需要实现hashcode方法。

有一种称为哈希码的东西 - 等于契约,两者都需要实现才能使哈希值工作,

答案here解释得很清楚。