解析 hashMap 源码之基本操作 get

时间:2022-07-23
本文章向大家介绍解析 hashMap 源码之基本操作 get,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

get

HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.get("a");

对应的 HashMap 源码

 public V get(Object key) {
     Node<K,V> e;
     return (e = getNode(hash(key), key)) == null ? null : e.value;
}

接下来就是 getNode 操作

 // 最好的 O(1) 最坏的 O(n)
    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;
    }

通过已经计算好的 hash 值,得到 table 的索引位置并来判断链表的第一个元素是不是要查找的节点,如果不是会查找树,最后会遍历链表