java缺少hashmap,奇怪的Java 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 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;

}

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.

EDIT: 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 data = new HashMap();

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值