简体   繁体   English

检查是否存在HashMap密钥

[英]Check the existence of a HashMap key

In Java, having a HashMap fully filled in with data of such form: 在Java中,使用这种形式的数据完全填充HashMap:

HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(1000000, 1);

what is faster when checking the existence of a random key, say 100: 检查随机密钥是否存在时更快,比如说100:

if (map.get(100) == null))

or 要么

if (!map.containsKey(100))

?

Question is interesting from the micro-optimization point of view. 从微观优化的角度来看问题很有意思。

The containsKey should be very slightly slower because it results in an extra function call (it just calls getEntry ) (it could get optimised away, I'm not sure whether Java will do so). containsKey应该稍微慢一点,因为它会导致额外的函数调用(它只调用getEntry )(它可以被优化掉,我不确定Java是否会这样做)。 containsKey looks like: containsKey看起来像:

public boolean containsKey(Object key) {
  return getEntry(key) != null;
}

But note that containsKey could on the other hand be very slightly faster on other Map implementations (but probably not those in the standard Java API). 但请注意,另一方面, containsKey在其他Map实现上可能会稍微快一点 (但可能不是标准Java API中的那些)。

Generally my implementations look like: (avoiding the need for containsKey ) 通常我的实现看起来像:(避免使用containsKey

int[] arr = map.get(100);
if (arr == null) // doesn't exist
  // do stuff
else // exists
  // do stuff with arr

The below would definitely be slower than the above: (if the items you look for exist a reasonable amount of the time) 下面肯定比上面慢:(如果您寻找的项目存在合理的时间)

if (!map.containsKey(100)) // doesn't exist
  // do stuff
else // exists
{
  int[] arr = map.get(100);
  // do stuff with arr
}

Edit: Thanks to zvzdhk for providing the source of containsKey . 编辑:感谢zvzdhk提供containsKey的源代码。 I should actually have checked. 我其实应该检查一下。

Actually both approaches are the same. 实际上两种方法都是一样的。 If you look in java.util.HashMap source code you can find next containsKey realization: 如果查看java.util.HashMap源代码,可以找到下一个containsKey实现:

public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

这两个只在return类型上有所不同,除了map.get(key)可以返回null ,如果它是一个键,但是map.containsKey(key)将返回boolean ,它可以用来distingush两个可能的map.get(key)返回null

There is no difference between this two approaches. 这两种方法没有区别。 The main difference only what you are going to do next. 主要区别仅在于您接下来要做什么。 If you need the value then, of course by get you will have the value. 如果你需要这个值,那么当然你会得到这个价值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM