- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我试图从包含一条记录的 HashMap 中获取错误时,我一直得到空值。最后我通过以下方式进行了测试:
Iterator<Position> it = pieces.keySet().iterator();
while (it.hasNext()){
System.out.println("object from key >> " + pieces.get(it.next()));
}
Iterator<Piece> itt = pieces.values().iterator();
while (itt.hasNext()){
System.out.println("direct object >> " + itt.next().getPosition());
}
我得到的输出是:
object from key >> null
direct object >> application.Position@37
我所展示的代码是按原样使用的,中间没有任何其他内容。
关于位置对象,我重写了 hashCode() 函数以根据 Position 类的值返回 hashCode。因此,当对象内的变量发生更改时,HashCode 也会发生更改。在位置对象的值更改之前,上面的代码运行良好。但是一旦我改变了,我就会通过 key 得到一个空值。
最佳答案
请参阅 Map
的相关文档:
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.
映射数据结构会在插入时检查您的对象,以确定它应该存在的位置(对于HashMap
,它会检查hashCode()
并将其放入特定的桶,对于TreeMap
,它将它与其他键进行比较,并将其放入树的特定分支中,等等)。 map 提供高效的查找,因为它们仅查找对象预期所在的位置,而不搜索其他存储桶/树的其余部分。如果您在将对象存储在映射中后以影响映射存储位置的方式对其进行变异,则会破坏映射所做的假设。它将在预期的存储桶中查找,找不到它,然后放弃。
我在此 related answer 中更详细地介绍了 HashMap
所做的假设以及原因。 .
关于Java HashMap 未从键获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34072891/
我是一名优秀的程序员,十分优秀!