繁体   English   中英

Java 6和Java 8中的HashMap get方法

[英]HashMap get method in Java 6 & Java 8

我正在查看Java 6和Java 8中的HashMap get方法,Java 8中的实现有点复杂,我无法获得它。

这来自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中,这里获取正确的Entry元素,并尝试根据给定的键查找相应的值。

这段代码来自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);

关于:

(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 = hash的条目散布在表的n个条目上。 (n-1)用于防止尝试插入tab [n]的极端情况-由于tab.length为n,这可能导致ArrayIndexOutOfBoundsException。

您所指的“额外逻辑”:

if (first.hash == hash && // always check first node
    ((k = first.key) == key || (key != null && key.equals(k))))
    return first;

上面的代码从表中返回第一个Node,它不仅与正在搜索的键的hashCode相匹配,而且与该键完全“相等”。

if ((e = first.next) != null) {
    if (first instanceof TreeNode)
        return ((TreeNode<K,V>)first).getTreeNode(hash, key);

如果存储桶已被“ Treeified”化,则以上内容将返回Node -在此类的“实施说明”中指定了注释之一所指出的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM