簡體   English   中英

相同的對象用作Map中兩個條目的鍵

[英]Same Object is used as key for two entries in Map

我有一個如下的Employee類。

class Employee {
int empId;
String empName;

public Employee() {
}

Employee(int empId, String empName) {
    this.empId = empId;
    this.empName = empName;
}

public int getEmpId() {
    return empId;
}

public void setEmpId(int empId) {
    this.empId = empId;
}

public String getEmpName() {
    return empName;
}

public void setEmpName(String empName) {
    this.empName = empName;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + empId;
    result = prime * result + ((empName == null) ? 0 : empName.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Employee other = (Employee) obj;
    if (empId != other.empId)
        return false;
    if (empName == null) {
        if (other.empName != null)
            return false;
    } else if (!empName.equals(other.empName))
        return false;
    return true;
}}

我在下面的HashMap中將此Employee類對象用作鍵。

    Map<Employee, String> empMap = new HashMap<>();
    Employee e1 = new Employee(123, "xyz");
    empMap.put(e1, "asd");
    System.out.println(empMap.size());
    System.out.println(empMap.get(e1));
    e1.setEmpId(122);
    empMap.put(e1, "asd");
    System.out.println(empMap.size());
    System.out.println(empMap.get(new Employee(122, "xyz")));
    System.out.println(empMap.get(new Employee(123, "xyz")));

    Set<Employee> mapEmpKeys = empMap.keySet();
    mapEmpKeys.forEach(emp -> {
        System.out.println("Employee ID: " + emp.getEmpId() + " Employee Name: " + emp.getEmpName());
    });

程序的輸出: 1 asd 2 asd null Employee ID: 122 Employee Name: xyz Employee ID: 122 Employee Name: xyz

我的問題是,即使作為鍵的對象相同,我也得到了map的大小為2。有人可以向我解釋一下,在將Employee對象e1設置為不同的值並將其再次添加到map中后,將Employee對象e1更改后,給出的大小為2,當我遍歷地圖的鍵集時,兩個條目都得到相同的對象。 鍵在地圖中必須唯一,對嗎? 那為什么我兩次獲得相同的對象密鑰? 謝謝!

在對用作HashMap的鍵的實例進行突變時,如果修改用於確定相等性或計算hashCode()屬性,則會破壞HashMap

第一次將密鑰放入Map時,將其放入與基於值123和“ xyz”計算的hashCode()相對應的存儲桶中。

第二次將相同的密鑰放入Map中時,將其放入與基於值122和“ xyz”計算出的hashCode()相對應的其他存儲桶中。

由於HashMap首先找到與某個鍵的hashCode()相匹配的存儲桶,並且僅在以后檢查該存儲桶中所有鍵的鍵是否相等,如果給定鍵的hashCode()已更改,則第二次調用put將嘗試在其中找到它。新存儲桶(與新的hashCode()匹配),並且在那里找不到它。 因此,相同的密鑰被添加兩次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM