gpt4 book ai didi

java - HashMap 为 Integer 键返回错误的值

转载 作者:行者123 更新时间:2023-11-30 08:41:15 25 4
gpt4 key购买 nike

我有一个 HashMap 下面的 HashMap

private Map<Integer, List<CustomClass>> map = new HashMap<>();

我正在尝试在 HashMap 中针对 Integer 键添加一个新条目,如果该键存在,那么我想获取相应的列表并在其中添加新项。代码如下。

        if (this.map.containsKey(//Integer Key)) {
this.map.get(//Integer Key).add(//New List Item);
} else {
List<CustomClass> customClass = new ArrayList<>();
customClass.add(new CustomClass());
this.map.put(//Integer Key, customClass);
}

真正的问题在于key已经存在的部分,我尝试使用HashMap get函数

this.map.get(//Integer Key).add(//New List Item);

如果找不到 Integer 键的值,它不会给出 null,但它经常给出错误的 ArrayList。现在我知道 HashMap 与 equals 和 hashCode 一起工作,所以我尝试重写这些函数并使用它们代替 Integery Key。

public class CustomHashMapIntegerKey {

private Integer key = 0;

public void setKey(Integer key) {
this.key = key;
}

public Integer getKey() {
return this.key;
}

@Override
public int hashCode() {
return this.key.hashCode();
}

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (null == obj) return false;
if (this.getClass() != obj.getClass()) return false;
final CustomHashMapIntegerKey customHashMapIntegerKey = (CustomHashMapIntegerKey) obj;
if (null == this.key && null != customHashMapIntegerKey.getKey()) return false;
if (null != this.key) {
if (!this.key.equals(customHashMapIntegerKey.getKey())) return false;
}
return true;
}
}

并更改了我的映射以使用这个新类作为键而不是整数,但我仍然遇到 HashMap 给出错误值的相同问题。此链接提供了一些详细的片段 https://gist.github.com/MAnfal/dc581234ce597a8ff062

最佳答案

HashMap 部分依赖于 equalshashCode 来完成它的工作,但它有点复杂。看看this article以获得深入的解释。

为了您的目的(以列表作为其值的 map ),我建议使用 Multimap来自 Google 的 Guava 库:

ListMultimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(4, "Is the first digit of '4'");
multimap.put(4, "Is the first digit of '42'");
multimap.put(4, "Is the first digit of '4711'");
multimap.put(1, "Is the first digit of '13'");

Collection<String> values = multimap.get(4);

Collection values 将包含您在键 4 下添加的三个元素。

关于java - HashMap 为 Integer 键返回错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35193830/

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