@lyxiang
2019-07-08T14:33:20.000000Z
字数 1512
阅读 1786
在一次开发过程中,出现了下面的bug。
Map<String, String> hashMap = new HashMap<>();
System.out.println(map.keySet().contains(null)); //output:false
ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
System.out.println(concurrentHashMap.keySet().contains(null) // throw NullPointerException
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean containsKey(Object key) {
return get(key) != null;
}
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode()); //存在NPE风险
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}