在使用map.get()时使用java Map.containsKey()多余 [英] Is using java Map.containsKey() redundant when using map.get()

查看:586
本文介绍了在使用map.get()时使用java Map.containsKey()多余的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在想,在最佳实践中是否允许在 java.util上使用 containsKey()方法。映射,而是对 get()的结果进行空检查。

I have been wondering for some time whether it is allowable within best practice to refrain from using the containsKey() method on java.util.Map and instead do a null check on the result from get().

我的理由是,查找值两次似乎是多余的 - 首先是 containsKey()然后再次为 get()

My rationale is that it seems redundant to do the lookup of the value twice - first for the containsKey() and then again for get().

另一方面,大多数标准的映射缓存最后一次查找,或者编译器可以去除冗余,而对于代码的可读性,最好保持 containsKey() 部分。

On the other hand it may be that most standard implementations of Map cache the last lookup or that the compiler can otherwise do away with the redundancy, and that for readability of the code it is preferable to maintain the containsKey() part.

我非常感谢您的意见。

推荐答案

某些Map实现被允许具有空值,例如HashMap,在这种情况下,如果 get(key)返回 null 它不保证与该键相关联的映射中没有条目。

Some Map implementations are allowed to have null values, eg HashMap, in this case if get(key) returns null it does not guarantee that there is no entry in the map associated with this key.

所以如果你想知道一个地图是否包含一个键,使用 Map.containsKey 。如果您只需要一个映射到键的值,则使用 Map.get(key) Map.containsKey 将无用,并会影响性能。此外,在并发访问地图(例如 ConcurrentHashMap )的情况下,测试 Map.containsKey(key)在您调用 Map.get(key)之前,有可能该条目将被另一个线程删除。

So if you want to know if a map contains a key use Map.containsKey. If you simply need a value mapped to a key use Map.get(key). Map.containsKey will be useless and will affect performance. Moreover, in case of concurrent access to a map (eg ConcurrentHashMap), after you tested Map.containsKey(key) there is chance that the entry will removed by another thread before you call Map.get(key).

这篇关于在使用map.get()时使用java Map.containsKey()多余的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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