HashMap中的关键存在检查 [英] Key existence check in HashMap

查看:79
本文介绍了HashMap中的关键存在检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个HashMap,里面有1000个条目,我正在寻找提高效率的方法。
如果非常频繁地访问HashMap,那么在每次访问时检查密钥的存在将导致大量开销。相反,如果钥匙不存在,并因此发生异常,我可以捕捉到异常。 (当我知道这很少会发生)。这将减少访问HashMap的一半。



这可能不是一个好的编程习惯,但它会帮助我减少访问次数。或者我在这里丢失了什么?



[更新]我在HashMap中没有空值。

解决方案

你有没有存储空值?如果没有,你可以这样做:

  Foo value = map.get(key); 
if(value!= null){
...
} else {
//没有这样的键
}

否则,如果您返回空值,您可以 检查是否存在:

  Foo value = map.get(key); 
if(value!= null){
...
} else {
//可能存在密钥...
if(map.containsKey(key )){
//好的,有一个键,但是它的值为空
} else {
//肯定没有这样的键
}
}


Is checking for key existence in HashMap always necessary?

I have a HashMap with say a 1000 entries and I am looking at improving the efficiency. If the HashMap is being accessed very frequently, then checking for the key existence at every access will lead to a large overhead. Instead if the key is not present and hence an exception occurs, I can catch the exception. (when I know that this will happen rarely). This will reduce accesses to the HashMap by half.

This might not be a good programming practice, but it will help me reduce the number of accesses. Or am I missing something here?

[Update] I do not have null values in the HashMap.

解决方案

Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // No such key
}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);
if (value != null) {
    ...
} else {
    // Key might be present...
    if (map.containsKey(key)) {
       // Okay, there's a key but the value is null
    } else {
       // Definitely no such key
    }
}

这篇关于HashMap中的关键存在检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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