假设我有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
- 对象排序取决于workEnd
和id
。
现在我想将这些Employee
- 对象作为键放在HashMap中。但是如果属性Employee
和put()
相等,我希望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);
}
}