我有一个 HashMap,我用它来存储 SplitCriteria 类型的对象,使用字符串作为键
Map<String, SplitCriteria> criteriaMap = new HashMap<String, SplitCriteria>();
示例 SplitCriteria 对象包含如下内容:
SplitCriteria [
id=4,
criteriaName="Location",
criteriaAbrevName="Loc",
fieldName="LOCATION",
isMandatory=false
]
id 是一个 long,isMandatory 是一个 boolean 值,其余都是字符串。
我正在遍历先前填充的相同对象类型的数组,总数为 7,使用 fieldName 属性作为键将每个数组添加到 HashMap:
for(SplitCriteria split : selectedCriteria){
String fieldName = split.getFieldName();
criteriaMap.put(fieldName, split);
}
此循环完成后, map 的大小看起来是 7,但查看表格内容时只有 6 对象存在。
通过研究这个问题,我了解到如果键发生冲突,冲突的对象将使用 next
“链接”在一起。 Map 中条目的属性。
从下图中,您可以看到这就是我的场景中发生的情况,但是这两个 key 完全不同!
另外我在 put 方法的文档中读到了这个
If the map previously contained a mapping for the key, the old value is replaced by the specified value
和
Returns: the previous value associated with key, or null if there was no mapping for key.
因此,如果 key 发生冲突,我希望返回旧条目,但事实并非如此。
我不知道这是怎么发生的,因为我使用的每个键都与下一个完全不同。
如果您能帮助解决这个问题,我们将不胜感激。
水稻
编辑: 当我稍后尝试检索对象时,我得到了一个空响应
SplitCriteria criteria = (SplitCriteria) criteriaMap.get(key);
最佳答案
but looking at the table contents there are only 6 objects present
不,看看 size
- 它是 7。您刚刚在同一个桶中有两个值。它们不会因精确的哈希值而发生冲突,但它们确实会因桶而发生冲突。没关系。
当您使用 map 时,您将无法观察到这一点 - 如果您只使用公共(public) API,您将看到所有 7 个条目,没有任何不妥之处。这就是为什么我通常建议避免使用调试器深入研究对象的内部细节,直到您确实真的确定存在问题。
关于java - HashMap.put() 正在覆盖不同键的现有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33016884/