在 containsKey() 检查哈希表后,get() 是否可以为空?
Can a get() ever be null after a containsKey() check in a Hashtable?
我在 android 应用程序中实现了哈希表,该应用程序最初是按以下方式填充的:
if(table.containsKey(key)){
table.get(key).add(item);
}else{
table.put(key, new ArrayList<Items>());
table.get(key).add(item);
}
(变量名略有改动)
Android Studio 对两种添加方法发出 Method invocation 'add' may produce NullPointerException
警告。我之前(也是唯一的)dict 类型结构的经验来自 Python,这从来都不是问题,但为了安全起见,我想检查一下:这真的有可能抛出 NPE 吗?
干杯
键可以出现在映射中,但值可以是 null
,如下图所示:
Map<String, String> hmap = new Hashtable<String, String>();
hmap.put("A", null);
if (hmap.containsKey("A")) {
hmap.get("A").length(); // this can cause a NPE
}
要解决此问题,您可以使用 computeIfAbsent()
让我们看看 Hashtable.get
的文档:
Returns the value to which the specified key is mapped, or null
if
this map contains no mapping for the key.
More formally, if this map contains a mapping from a key k to a value
v such that (key.equals(k))
, then this method returns v; otherwise it
returns null. (There can be at most one such mapping.)
所以如果Hashtable中的一个KVP的值为null,那么if分支就会出现NPE。
如果 key
为空,containsKey
和 put
也会抛出 NPE,因此在 else 分支中也可能发生 NPE。
我在 android 应用程序中实现了哈希表,该应用程序最初是按以下方式填充的:
if(table.containsKey(key)){
table.get(key).add(item);
}else{
table.put(key, new ArrayList<Items>());
table.get(key).add(item);
}
(变量名略有改动)
Android Studio 对两种添加方法发出 Method invocation 'add' may produce NullPointerException
警告。我之前(也是唯一的)dict 类型结构的经验来自 Python,这从来都不是问题,但为了安全起见,我想检查一下:这真的有可能抛出 NPE 吗?
干杯
键可以出现在映射中,但值可以是 null
,如下图所示:
Map<String, String> hmap = new Hashtable<String, String>();
hmap.put("A", null);
if (hmap.containsKey("A")) {
hmap.get("A").length(); // this can cause a NPE
}
要解决此问题,您可以使用 computeIfAbsent()
让我们看看 Hashtable.get
的文档:
Returns the value to which the specified key is mapped, or
null
if this map contains no mapping for the key.More formally, if this map contains a mapping from a key k to a value v such that
(key.equals(k))
, then this method returns v; otherwise it returns null. (There can be at most one such mapping.)
所以如果Hashtable中的一个KVP的值为null,那么if分支就会出现NPE。
如果key
为空,containsKey
和 put
也会抛出 NPE,因此在 else 分支中也可能发生 NPE。