2016-12-02 60 views
0

我正在查看Java 6中的HashMap get方法& Java 8中,Java 8中的實現有點複雜,我無法獲得它。Java 6和Java 8中的HashMap get方法

這是Java 6

public V get(Object key) { 
    if (key == null) 
     return getForNullKey(); 
    int hash = hash(key.hashCode()); 
    for (Entry<K,V> e = table[indexFor(hash, table.length)]; 
     e != null; 
     e = e.next) { 
     Object k; 
     if (e.hash == hash && ((k = e.key) == key || key.equals(k))) 
      return e.value; 
    } 
    return null; 
} 

在這裏,在Java 6中,這是獲得正確的輸入元件,並試圖找出基於給定鍵對應的值。

如果從Java 8此代碼:

public V get(Object key) { 
     Node<K,V> e; 
     return (e = getNode(hash(key), key)) == null ? null : 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; 
    } 

我無法理解Java中的邏輯8.

他們是如何考慮的第一要素:

(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); 
+1

您是否閱讀過您鏈接到的源代碼中的實現說明?它很清楚地解釋了它是什麼以及它是什麼。 – biziclop

+0

@biziclop,你指的是與get方法相關的註釋嗎?沒有關於這種新方法的解釋。你能告訴我你指的是哪一個? – user3181365

+2

不,在課程頂部有一個名爲「實施說明」的長評論,他們在這裏解釋整個「TreeNode」業務。 – biziclop

回答

0

關於:

(first = tab[(n - 1) & hash]) != null) 

即來自條目怎樣添加到表中,如下所示:

if ((p = tab[i = (n - 1) & hash]) == null) 
    tab[i] = newNode(hash, key, value, null); 

AND-ING(N-1)和散列允許具有的hashCode =散列條目分散在表格的n個條目中。 (n-1)用於防止試圖插入tab [n]的邊緣情況 - 這可能導致ArrayIndexOutOfBoundsException,因爲tab.length是n。

「額外邏輯」你指的是:

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); 

以上返回節點如果桶已經「Treeified」 - 細節哪些是指向一個評論在這個類的「實施注意事項」中指定。