在解決哈希沖突時有一種方法叫鏈地址法,就是把相同key的value用鏈表串起來。那么,當用這些相同的key取值時,會得到這個鏈表,可是鏈表里有多個值,要返回哪一個值給用戶?
3 回答

慕雪6442864
TA貢獻1812條經驗 獲得超5個贊
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 && //檢查第一個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; }
源碼是通過hash和equals比較返回的
添加回答
舉報
0/150
提交
取消