【发布时间】:2016-03-08 11:22:32
【问题描述】:
当我试图从带有一条记录的哈希映射中获取错误时,我一直为空。最后我通过以下方式对其进行了测试:
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 也会发生变化。上面的代码在位置对象的值改变之前运行良好。但是一旦我改变了我通过密钥得到一个空值。
【问题讨论】:
-
一旦密钥在
Map中,您绝对不能更改计算hashCode的任何值。您必须remove并重新add密钥。 -
所以你的意思是说 HashMap 对象在插入时保存 hashCodes 并且在我调用 HashMap 的 get() 函数时不调用 hashCode() 函数?
-
您认为
HashMap的工作原理如何?它如何实现(摊销)O(1)性能? -
好吧,我不知道 HashMap 是如何工作的。这就是我问的原因。我也不知道它的表现顺序。那么是不是每次调用get()都会调用hashCode()函数呢?
-
阅读this。它应该回答你所有的问题。从a tutorial 开始而不是直接来这里也很有帮助。
标签: java dictionary hash hashmap hashcode