简体   繁体   English

HashMap null值问题

[英]HashMap null value issue

What is the difference between both of result. 两个结果之间有什么区别。

  1. When I've null value with key 当我用键空值时

  2. When key itself is not exist 当密钥本身不存在时

In above both condition result is null. 在上面两个条件结果都是null。 So how can i identify my key value 那么如何识别我的关键价值呢?

Map map = new HashMap();
map.put(1,null);
System.out.println(map.get(1));
System.out.println(map.get(2));

Answer: 回答:

null

null

While get returns the same result for null value and non-existing key, containsKey doesn't: getnull值和不存在的键返回相同的结果, containsKey不:

map.containsKey(1) would return true . map.containsKey(1)将返回true

map.containsKey(2) would return false . map.containsKey(2)将返回false

In addition, if you iterate over the keys of the Map (using keySet() ), 1 will be there and 2 won't. 另外,如果迭代Map的键(使用keySet() ),则1将存在, 2则不会。

Hashmap returns null if no Value is mapped to the key. 如果没有Value映射到键,则Hashmap返回null。 So this can be solved by your code also: 所以这可以通过你的代码来解决:

if( map.get(1) != null ){
     //
}

Reference Here 参考这里

Make a check for if the value is null to avoid the null prints. 检查值是否为null以避免空打印。

pseudo code: 伪代码:

//For inputting
if(object != null){
   map.put(1, object);
}
//For getting the value
if(value != null){
     map.get(value)
  }

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

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