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

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

问题描述

是否总是需要检查 HashMap 中的键是否存在?

Is checking for key existence in HashMap always necessary?

我有一个包含 1000 个条目的 HashMap,我正在考虑提高效率.如果 HashMap 被非常频繁地访问,那么在每次访问时检查 key 是否存在将导致很大的开销.相反,如果密钥不存在并因此发生异常,我可以捕获异常.(当我知道这种情况很少发生时).这将使对 HashMap 的访问减少一半.

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?

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

[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天全站免登陆