嘿,我正在使用 aHashMap
来跟踪公告板上的服务和服务请求。但是,我必须有哈希码和等于错误,因为我得到了重复的键。谁能告诉这可能是为什么?
keySet的内容:
Services: [1, 1, 6, 6, 3]
Requests: [8, 7, 6, 5, 8, 4, 5, 6, 2]
以下是相关代码:
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;
}
}