gpt4 book ai didi

java - 为什么我的 HashMap 允许重复键?

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:11 25 4
gpt4 key购买 nike

嘿,我正在使用 HashMap 来跟踪 BulletinBoard 上的服务和服务请求。但是,我必须有哈希码并且等于错误,因为我得到了重复的键。谁能说出为什么会这样?

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;
}
}

最佳答案

最可能的原因是您用作键的对象是可变的。因此,如果您执行以下操作:

map.put(anAdvert, 1);
anAdvert.spawn(); //modifies id, which affects hashcode and equals

map 的行为将是意外的。

比照Map's 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.

关于java - 为什么我的 HashMap 允许重复键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12426734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com