HashMap源码之常用方法--JDK1.8

常用方法

hash(key)

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

该方法中返回的值是将得到的hash值(传入的值的hashCode方法)的高16位与低16位进行异或操作。这样做的目的在于减少hash之间的碰撞。具体可看这篇:为什么hash将高16位与低16位进行异或操作

V put(K key, V value)

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                //hashmap中为空方法,在LinkedHashMap中进行了实现,作用为将传入的节点移动到末尾
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

参数:

  • hash:通过对传入的key进行hash得到的值
  • onlyIfAbsent:如果该值为true,插入数据时只有当key不存在是才插入,否则不进行插入操作

该方法中首先判断当前map中是否存在key,如果不存在则创建一个节点,如果存在根据onlyIfAbsent参数来决定是否进行更新操作。在hashmap中使用数组+链表的形式来保存数据,在保存数据时,对该数进行hash并(n - 1) & hash确定需要插入的数据在数组中的位置。(n - 1) & hash保证得到的数据是散列的且一定在数组中,两个数进行&操作得到的结果一定是小于等于较小的数。而数组存储的实际是一个链表,当数组位置存储的有数据时而另外一个数据也要插入该位置时则链在当前数据的后面。实际存储的事一个包含下一个节点引用的Node节点。当一条链表上存储的节点超过8个时这条链表将会转化为红黑树,更有利于索引与修改等操作。
当计算得到的数组位置没有数据时,直接插入一个新的节点:

tab[i] = newNode(hash, key, value, null);

当需要插入的key-value在map中已有时,进行覆盖操作:

if (p.hash == hash &&
        ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

如果需要插入的数组位置的链表已经转化为红黑树则调用树的插入操作,由于红黑树比较麻烦,这里不进行深入介绍,后面会补上。

else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

后面的代码就是将需要插入的值包装为一个节点,然后链接到指定数组位置链表的尾节点:

for (int binCount = 0; ; ++binCount) {
    if ((e = p.next) == null) {
        //将key-value包装为node放在p的后面
        p.next = newNode(hash, key, value, null);
        //如果该链表的大小达到链表-->红黑树的阈值则进行转化 
        //TREEIFY_THRESHOLD默认情况下为8
        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
            treeifyBin(tab, hash);
            break;
        }
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            break;
            p = e;
    }

V get(Object key)

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

hashmap中的get方法通过调用内部的getNode方法实现,first = tab[(n - 1) & hash]取出key所对应的值。找到需要的值分为以下几步:

  1. 首先比较取到的first的key与我们传入的key是否相等,如果相等则直接返回first
  2. 上一步同如果不等,再判断当前first所处的数组位置上的链表是否已经转变为红黑树,如果已经转换为红黑树,那么则调用红黑树的操作来搜索key对应的值,找到则将对应的value返回,没有则返回null
  3. 如果该位置仍为链表,则通过遍历该链表查找key,找到则将对应的value返回,没有则返回null

boolean containsXxx(Object obj)

    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }
    
    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            //遍历数组
            for (int i = 0; i < tab.length; ++i) {
                //遍历每个数组中的所有元素,查找value
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

containsKey方法同样是调用上面分析的getNode(key)方法,查找步骤一致,找到返回true,没找到则返回false;

V remove(Object key)

    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null?null : e.value;
    }
    //matchValue:为true的情况下必须key-value完全匹配才能进行删除
    //movable:只有当链表转化为红黑树,在对树进行操作是才使用该参数,movable为false时在删除指定节点时不移动其他节点
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        //p为计算所得数组位置链表上的第一个元素
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            //判断p是否是需要删除的元素
            if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                //链表已转化为红黑树,从红黑树中找需要的节点
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    //遍历链表查找需要的节点
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||(value != null && value.equals(v)))) {
                //需要删除的节点找到了,进行删除操作
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                //进行了一次修改操作modCount加1
                ++modCount;
                //元素中的数量减1
                --size;
                //该方法在HashMap中为空方法
                //LinkedHashMap中进行了实现,确保在删除过程中LinkedHashMap中进行了实现的首位节点不会发生指向错误
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }
原文地址:https://www.cnblogs.com/liyus/p/9916375.html