問題描述
嘿,我正在使用 HashMap
來跟蹤公告板上的服務(wù)和服務(wù)請求.但是,我必須有哈希碼和等于錯誤,因?yàn)槲业玫搅酥貜?fù)的鍵.誰能告訴這可能是為什么?
Hey I'm using a HashMap
to keep track of services and service-requests on a BulletinBoard. However, I must have the hashcode and equals wrong because I'm getting duplicate keys. Can anyone tell why this might be?
keySet的內(nèi)容:
Services: [1, 1, 6, 6, 3]
Requests: [8, 7, 6, 5, 8, 4, 5, 6, 2]
以下是相關(guān)代碼:
private static final HashMap<Advert, Integer> services = new HashMap<>();
...
public class Advert {
private int id;
private BoardPoster poster;
public Advert(BoardPoster poster) {
this.poster = poster;
}
public BoardPoster getPoster() {
return poster;
}
public void spawn() {
id = RANDOM.nextInt(ADVERT_RANGE);
}
public int getID() {
return id;
}
@Override
public String toString() {
return Integer.toString(id);
}
@Override
public boolean equals(Object o) {
if (o != null && o instanceof Advert) {
return ((Advert) o).id == id;
}
return false;
}
@Override
public int hashCode() {
return 67 * 5 + this.id;
}
}
推薦答案
最可能的原因是您用作鍵的對象是可變的.因此,如果您執(zhí)行以下操作:
The likeliest reason is that the objects you use as keys are mutable. So if you do something like:
map.put(anAdvert, 1);
anAdvert.spawn(); //modifies id, which affects hashcode and equals
地圖的行為會出乎意料.
The behaviour of the map will be unexpected.
cf 地圖的javadoc
注意:如果將可變對象用作映射鍵,則必須非常小心.如果對象的值以影響等于比較的方式更改,而對象是映射中的鍵,則不會指定映射的行為.
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
這篇關(guān)于為什么我的 HashMap 允許重復(fù)鍵?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!