我有一个对象,它有一个字段 - double[] _myField 它的哈希码是
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(_myField);
return result;
}
但是,如果我使用该对象作为 Map 中的键,我会得到以下奇怪的行为:
for (Map.Entry<MyObject, String> entry: _myMap.entrySet())
{
if (entry.getValue() != _myMap.get(entry.getKey()))
{
System.out.println("found the problem the value is null");
}
}
我认为上述 IF 语句正确的唯一原因是我得到了不同的 key 哈希码。
事实上,我已经将 hashcode 函数更改为在所有情况下都返回 1。效率不高,但有利于调试,而且 IF 语句确实总是错误。
Arrays.hashcode() 有什么问题吗?
请注意(阅读一些评论后): 1) 至于 IF 语句中 != 的用法,确实是比较引用,但在上面的情况下应该是相同的。无论如何,奇怪的是右侧返回 NULL 2)至于发布Equals函数。当然我已经实现了。但这无关紧要。在调试中跟踪代码表明只调用了 hashcode。其原因大概是奇怪的事情,返回的哈希码与原始的不同。在这种情况下,Map 找不到匹配的条目,因此无需调用 Equals。
最佳答案
数组在 map 中时是否被更改?因为这会改变结果的结果。
关于Java Arrays.hashcode() 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7981013/