奇怪的Java HashMap行为-找不到匹配的对象 [英] Strange Java HashMap behavior - can't find matching object

查看:158
本文介绍了奇怪的Java HashMap行为-找不到匹配的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在java.util.HashMap中查找键时遇到了一些奇怪的行为,我想我缺少了一些东西.该代码段基本上是:

I've been encountering some strange behavior when trying to find a key inside a java.util.HashMap, and I guess I'm missing something. The code segment is basically:

HashMap<Key, Value> data = ...
Key k1 = ...

Value v = data.get(k1);
boolean bool1 = data.containsKey(k1);
for (Key k2 : data.keySet()) {
    boolean bool2 = k1.equals(k2);
    boolean bool3 = k2.equals(k1);
    boolean bool4 = k1.hashCode() == k2.hashCode();
    break;
}

那儿有一个奇怪的for循环,因为对于特定的执行,我碰巧知道data此时仅包含一项,它是k1,实际上是bool2,<在该执行中,c4>和bool4将被评估为true.但是,bool1将被评估为false,而v将为空.

That strange for loop is there because for a specific execution I happen to know that data contains only one item at this point and it is k1, and indeed bool2, bool3 and bool4 will be evaluated to true in that execution. bool1, however, will be evaluated to false, and v will be null.

现在,这是更大程序的一部分-我无法在更小的样本上重现错误-但在我看来无论程序的其余部分做什么,这种行为都永远不会发生.

Now, this is part of a bigger program - I could not reproduce the error on a smaller sample - but still it seems to me that no matter what the rest of the program does, this behavior should never happen.

编辑:我已经手动验证了哈希码在将对象插入地图的时间和查询时间之间不会发生变化.我会继续检查这个场地,但是还有其他选择吗?

I have manually verified that the hash code does not change between the time the object was inserted to the map and the time it was queried. I'll keep checking this venue, but is there any other option?

推荐答案

如果在将键的哈希码插入到地图中后更改了哈希码,则可能会发生这种情况.

This behavior could happen if the hash code of the key were changed after it was inserted in to the map.

这是您描述的行为的一个示例:

Here's an example with the behavior you described:

public class Key
{
int hashCode = 0;

@Override
public int hashCode() {
    return hashCode;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Key other = (Key) obj;
    return hashCode == other.hashCode;
}

public static void main(String[] args) throws Exception {
    HashMap<Key, Integer> data = new HashMap<Key, Integer>();
    Key k1 = new Key();
    data.put(k1, 1);

    k1.hashCode = 1;

    boolean bool1 = data.containsKey(k1);
    for (Key k2 : data.keySet()) {
        boolean bool2 = k1.equals(k2);
        boolean bool3 = k2.equals(k1);
        boolean bool4 = k1.hashCode() == k2.hashCode();

        System.out.println("bool1: " + bool1);
        System.out.println("bool2: " + bool2);
        System.out.println("bool3: " + bool3);
        System.out.println("bool4: " + bool4);

        break;
    }
}
}

这篇关于奇怪的Java HashMap行为-找不到匹配的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆