HashMap<String, String> map = new HashMap<>();
map.put("1", "111");
手误操作——
map.get(1); // 输出为null
处理错误同时, 重新查看一下get函数逻辑 (jdk 1.8)
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
transient Node<K,V>[] table;// get方法中 进行查询操作的数组
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next; // 下一个结点
……
}
反映了 map 是数组+ 链表结构
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) {// 检查hash在哪个桶
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) { // 遍历此链表中结点 查找目标key
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;
}