[英]Understanding the workings of equals and hashCode in a HashMap
[英]Java HashMap return value not confirming with my understanding of equals and hashcode
以下代碼示例的輸出是:
{1--e = e2,2--e1 = e1}
package com.sid.practice;
import java.util.HashMap;
import java.util.Map;
public class InputOutputPractice
{
public InputOutputPractice()
{
}
public static void main(String[] args)
{
Employee e = new InputOutputPractice().new Employee(1, "e");
Employee e1 = new InputOutputPractice().new Employee(2, "e1");
Employee e2 = new InputOutputPractice().new Employee(1, "e2");
Map m = new HashMap();
m.put(e, "e");
m.put(e1, "e1");
m.put(e2, "e2");
System.out.println(m);
}
class Employee
{
public Employee(int id, String name)
{
this.id=id;
this.name = name;
}
private int id;
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
@Override
public boolean equals(Object obj)
{
return ((Employee)obj).getId()==(this.getId());
}
@Override
public int hashCode()
{
return Integer.valueOf(getId()).hashCode();
}
@Override
public String toString()
{
return this.id + "--" + this.name;
}
}
}
我不了解對象e2
如何覆蓋對象e
的鍵,但不能覆蓋值。 以我的理解,輸出應該是:
{1--e2 = e2,2--e1 = e1}
實際上,您將其倒退了。 該值被覆蓋。 密鑰沒有被替換,因為就HashMap
而言,e和e2是相同的。
您的輸出為{1--e=e2, 2--e1=e1}
:
key = e, value = "e2" (which overrode the old value "e")
key = e1, value = "e1"
當java.util.HashMap實現等於put()調用中提供的鍵時,它不會替換現有鍵。 因此,您的第三個put()檢查地圖的現有內容,找到一個現有的相等鍵,然后更新關聯的值。
這說明了為什么equals()和hashCode()通常應考慮所有屬性,因為許多util類認為被認為相等的對象是可互換的。
輸出{1 --- e = e2,2--e1 = e1}的原因是:
Map不會替換鍵,而是僅在現有Map中存在匹配項(基於鍵)時才對值進行替換。 因此適用於這種情況:
這里e等於Map的e2。 當地圖搜索位置時放置m.put(e2,“ e2”); 它轉到存在e-“ e1”的位置,並用“ e2”替換“ e1”並保留密鑰,即e在這種情況下保持不變
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.