簡體   English   中英

HashMap中的對象引用

[英]Object references in HashMap

以下代碼如何提供Employee對象e2作為員工的價值,即使我沒有將e2添加到HashMap。 我想知道e2是如何在這里提到的。

import java.util.HashMap;

    public class Employee {
    int phno;
    String name;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    Employee e1=new Employee();
   e1.name="niks";
   e1.phno=9032944566;
   HashMap<Employee,String> m=new HashMap();
   m.put(e1, "employee1");
   Employee e2=new Employee();
   e2.name="niks";
   e2.phno=9032944566;
   System.out.println("value of e2:"+m.get(e2));
    }

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + phno;
    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 (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (phno != other.phno)
        return false;
    return true;
}
 }

e2的輸出值:employee1

它們具有不同的引用,但它們的值是等於,因為您重寫了equals方法。

方法get()要做的是調用你的haschodeequals方法。 如果Map中兩個Objects的hashCode返回相同的數字,那么將調用equals來確定它們是否相等...

Employee newReference = new Employee();
Employee newReference2 = new Employee();
newReference.name="MyName";
newReference2.name="MyName";

map.put(newReference);
map.get(newReference2); //key.equals(key2)

這里有兩點需要注意:

1)Employee對象的兩個實例 - e1和e2是相等的 - 因為它們符合Employee類的equals()hashcode()方法中定義的條件。

2)散列映射不能有重復的密鑰。 因此,只要使用相同的鍵(e2,與e1是同一個對象調用put() ,它就會在地圖中被替換。

因為他們的phno編號和名稱是相同的,他們創建相同的哈希碼

測試這段代碼,看看我的意思

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    System.out.println("res : "+result);
    result = prime * result + phno;
    System.out.println("res : "+result);
    return result;
}

輸出:

res : 3381378
res : 104823717
res : 3381378
res : 104823717
value of e2:employee1

暫無
暫無

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

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