在 put
和 get
中判斷是否找到該對象的映射關係的條件寫法java
e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k)))
node
理解:
先判斷對象的 hash值 是否相等,hash值不相等
,說明不是同一個對象hash 值相等
但不必定爲同一個對象 ( hash 衝突
還須要進一步判斷對象是否相等(key),以及它的內容是否同樣數組
Map map = new HashMap(); map.put("o","lankeren"); map.get("o"); //lankeren
debug
進入 get 方法內部debug
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
進入hash方法,經過對象的hashCode算出hash值接着進入 getNode
方法code
/** * map.get **/ final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; // 若是table數組爲空,或者該key的映射位置爲null,直接return 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)))) // 若是key相等,找到 return e; } while ((e = e.next) != null); } } return null; }
樹結構 getTreeNode
先不研究 對象
put / get 好像主要就是經過傳入的 key / key-value 在方法內部的結構體Node -- 全局變量 table數組的操做
table 經過tab = table
, 將每一個方法中 tab 的處理結果存到 table 中,以便下次繼續tab = table
取數據
返回: 沒有對應的哈希映射,返回null,有哈希映射,返回 value
get