JDK 方法中的小坑
Map.getOrDefault
如果key对应的value本身为空而不是不存在这个key,那么getOrDefault会返回null
# 如果key对应的value本身为空而不是不存在这个key,那么getOrDefault会返回null
@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
测试
HashMap<String, String> map = new HashMap<>();
map.put("huakai",null);
System.out.println("mapValue=" + map.getOrDefault("huakai", "default"));
结果
mapValue=null