【发布时间】:2016-05-13 15:22:21
【问题描述】:
我有一个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);
}
真正的问题在于密钥已经存在的部分,我尝试使用 HashMap 获取函数
this.map.get(//Integer Key).add(//New List Item);
如果找不到 Integer 键的值,则不给出 null,但它经常给出错误的 ArrayList。现在我知道 HashMap 可以与 equals 和 hashCode 一起使用,所以我尝试覆盖这些函数并使用它们而不是整数键。
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 中存在错误,您可以在 Google 搜索中找到相关信息(并且已经修复)。 java.lang.Integer 也是极不可能有错误的东西。问题的最可能原因是您向
Map.get()方法提供了错误的整数。 -
我使用调试器进行了双重检查,包括我的键的 instanceof、value、布尔值与从 hashmap 获得的值。我并不是说它的 java 的错,但不知何故,我尝试的一切都没有给我适当的结果。
-
哈希取决于键,如果它是一个整数,那么“给[你]一个错误的 ArrayList”的可能性很小。重新检查您的代码。
-
如果可能的话,分享你的整个代码
-
Integer类已经实现了equals和hashcode方法,所以不需要CustomHashMapIntegerKey。除非应用程序逻辑做错了什么,否则它应该可以工作。可能是多线程问题。是否有多个线程试图读取和写入 HashMap。如果是这样,请考虑使用synchronized Map或更好的ConcurrentHashMap