[英]Using Objects as keys in Java HashMap
package test;
import java.util.HashMap;
public class test {
public static void main(String args[]) {
HashMap<ID, String> h = new HashMap<ID, String> ();
String b;
ID id1 = new ID(100);
ID id2 = new ID(200);
ID id3 = new ID(200);
h.put(id1, "apple");
h.put(id2, "pear");
**System.out.println(h.containsKey(id3));**
}
}
class ID {
Integer code;
public ID(Integer id) {
this.code = id;
}
@Override
public int hashCode()
{
return code.hashCode();
}
@Override
public boolean equals(Object o)
{
return this.code.equals(o);
}
}
該程序的輸出是“假”。 我無法理解這個結果。 我實現了hashCode和equals,它們被覆蓋了。 我不知道如何解決。 如何在java HashMap中使用對象作為鍵?
你的equals實現是錯誤的:
public boolean equals(Object o)
{
return this.code.equals(o); // this will never return true,
// since you are comparing an Integer instance
// to an ID instance
}
您應該將此代碼與其他代碼進行比較:
public boolean equals(Object o)
{
if (!(o instanceof ID))
return false;
ID oid = (ID) o;
return this.code.equals(oid.code);
}
錯誤的equals
方法的實現。 根據您的實現,它執行Integer
類equals方法。 我們應該在沒有執行庫類equals
方法的情況下處理邏輯。
@Override
public boolean equals(Object o) {
if (o == null || ((o instanceof ID) && o.hashCode() != this.hashCode())) {
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.