针对Java8的HashMap get与put方法分析

和JDK1.6的HashMap结构不同的是,JDK1.6中HashMap采用的是位桶+链表的方式,即我们常说的散列链表的方式,而JDK1.8中采用的是位桶+链表/红黑树的方式,也是非线程安全的。当某个位桶的链表的长度达到某个阀值的时候,这个链表就将转换成红黑树。

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    private static final long serialVersionUID = 362498820763181265L;

    /**
     * 初始容量16,位移运算,效率高于乘除运算
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * 默认负载因子0.75。当存入HashMap的元素占比超过整个容量的75%时,            
     * 进行扩容,而且在不超过int类型的范围时,进行2次幂的扩展
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    static final int TREEIFY_THRESHOLD = 8;

    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * 内部类,链表节点
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        //哈希值
        final int hash;
        //key值
        final K key;
        //value值
        V value;
        //下一节点
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        ...
    }

    /**
     * 存放Node<K, V>节点的table,是个数组,总是以2的幂次方扩容
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

    /**
     * 用于fail-fast机制,在ArrayList、LinkedList中均能看到,记录修改次数,若
     * 使用迭代器中有其他线程修改了map,则抛出ConcurrentModificationException
     */
    transient int modCount;

    //负载因子
    final float loadFactor;

    /**
     * 红黑树节点
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }
    }

    //计算哈希值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    ...
}

 put操作

public V put(K key, V value) {
        //哈希值,key,value
        // 参数onlyIfAbsent表示是否替换原值
        // 参数evict我们可以忽略它,它主要用来区别通过put添加还是创建时初始化数据的
        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;
        //若table为空,初始化容量,n为16
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //取模运算:(n-1) & hash(找到位桶),实际位置是hash % (length-1),该节点为空,插入 
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            // 否则该位置有节点p;
            //e是用来查看是不是待插入的元素已经有了,有就替换
            Node<K,V> e; K k;
            //若该节点p的hash值、key值和要插入节点的都相同,就将原节点替换为新节点
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                //此时代替换节点就是p了
                e = p;
            else if (p instanceof TreeNode)
                //若p节点是树节点
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //否则就是链表,遍历链表
                for (int binCount = 0; ; ++binCount) {
                    //p节点的next节点是空的话,新建节点挂在链表最后
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //若链表长度大于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;
                }
            }
            //代替换节点不为空,则将值进行替换
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        //modCount加1
        ++modCount;
        //若容量超过threshold,扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

1、先计算hash值,再将hash值与table数组-1进行按位与操作,找到对应的数组下标,若当前位置无节点直接插入;

2、否则有节点,即哈希碰撞,equals判断key值,若相等则替换当前节点;

3、若是树节点,插入数;

4、若是链表,循环遍历,插入链表尾部;若链表长度超过阈值,转为红黑树;若存在,则跳出。

5、若容量超过threshold(capacity * load factor)当前容量*负载因子,扩容

get操作

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;
        //根据hash值查找对应位桶上的节点不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            //位桶上第一个节点key值equals,直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            //位桶上第一个节点有后续节点
            if ((e = first.next) != null) {
                //后续节点是树节点,getTreeNode方法查找相应key
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                //循环遍历链表
                do {
                    //hash值与key值相等,找到,返回
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值