java基础 - HashMap

Hash? Map? HashMap?

Hash
又叫哈希、散列,它的作用是使用有限的特征去映射无限的信息,这个过程需要借助算法来实现,这个算法就叫做哈希算法。
hash算法没有固定公式,可以理解为一种思想。
hash碰撞
既然输入是无限的,而我们使用的特征空间是有限的,那么不管使用的hash算法多么复杂和精妙,都有可能出现不同的输入信息计算出的特征是相同的,这就是hash碰撞,也叫hash冲突。比如不同的java对象,调用Object类的hashCode()方法,就有可能计算出相同的hash值。
Map
一个java接口,用来保存映射关系,这里说的映射关系,指的是 <key, value>形式键值对,具体怎么保存,需要由实现类来实现。
HashMap
Map接口的实现类,它内部会初始化一个Node结点类型的数组,k-v键值对就保存在Node中。这些Node结点在数组中的位置,是通过对k-v中的key进行hash运算,根据计算出的值来确定的,所以叫做HashMap。

HashMap的结构

以JDK 1.8为例,HashMap内部定义了一个 Node<K,V>[] 类型的成员变量,这是一个结点数组。而定义Node<K,V>的部分源码如下:

    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

可以看到Node<K,V>对象中保存了我们要放入的 key,value,以及一个hash值,一个指向下一个结点的指针;而这些属性都是通过构造函数传入的。
除了数组以外,遇到hash冲突时,HashMap使用了链表的方式存储hash冲突的元素,当链表数量超过阈值时,还可能会对链表进行树化,转换成红黑树结构来存储。整体结构图如下(实际红黑树叶子结点必须为黑色,此处仅为示意):
在这里插入图片描述

HashMap的构造方法

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

构造方法中,并没有对存放数据的Node数组进行初始化,而仅仅是确定了两个属性 loadFactor 和 threshold。当我们执行 put 方法放入元素时,检测到Node数组为null,才会调用 resize方法进行扩容,完成数组创建。

loadFactor:加载因子,默认值为0.75;
threshold:扩容阈值,计算方式为 容量 * 加载因子。容量默认为16,也就是说扩容阈值默认为12。
当我们在HashMap的构造函数中传入了初始容量 initialCapacity时,threshold会被计算出来,比如传入20,计算出的初始 threshold就是32;传入32,则算出来也是32;也就是说,tableSizeFor方法计算结果总是>=初始容量的最近的2的幂。这时的threshold仅仅起一个计数的所用,用来代表应该分配的初始容量,正确的 threshold (扩容阈值)会在首次扩容的时候确定下来(容量 * 加载因子)。

HashMap的put方法

    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;
        //数组为空或长度为0,先扩容。
        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;
            //槽中已有元素,判断是否为相同的key,是则直接覆盖。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果不是相同key,但是已有元素为树结点,则进行红黑树结点的覆盖/插入。
            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);
                        //TREEIFY_THRESHOLD默认为8,binCount等于7时,此时链表上已经有9个结点,需要进行树化。
                        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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

put方法中确定下标使用的运算是:(n - 1) & hash,相当于是拿hash值对数组长度进行%取模运算,只是直接使用位运算更加高效。
这里的hash则是通过调用key的hashCode方法,然后位运算得到:

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

用流程图的方式描述 put方法的流程如下:
在这里插入图片描述

HashMap扩容

由put方法的流程可知,调用resize方法扩容出现在首次put,以及put后元素个数大于扩容阈值时,扩容的核心操作是创建一个更大的数组(HashMap采用2倍扩容),然后把原来的元素放到新数组中正确的位置上。源码如下:

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //如果Node数组已存在,2倍扩容得到新数组长度。
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //初始化,构造函数中指定初始容量走此逻辑
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        //初始化,构造函数中未指定初始容量走此逻辑
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        //确保扩容阈值被计算
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    //如果原来的结点为单结点,直接重新计算hash值,放到新数组中。
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    /*
                    如果原来的结点为树形结点,进入树的迁移逻辑,如果迁移后发现节点数<=解除树化阈值
                    (UNTREEIFY_THRESHOLD,默认为6),则将红黑树拆成链表结构。
                    */
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    //链表走此逻辑。
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            /*
                            原链表中结点的hash值重新加算后,可能会拆解为两个链表,一个头结点还在原下标处(低处),而另一个头结点的下
                            标为原下标+原数组长度(高处),这里(e.hash & oldCap) == 0成立,则表示这个结点应该继续待在低处,反之在高处。
                            */
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

关于(e.hash & oldCap) == 0的理解:
在这里插入图片描述

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

ConcurrentHashMap

ConcurrentHashMap是HashMap的线程安全版本,它的基本结构与HashMap一致,都使用了数组+链表+红黑树的结构,不过ConcurrentHashMap使用了volatile变量 + CAS原子操作 + synchronized锁来保证线程安全。

ConcurrentHashMap中使用了一个名为sizeCtl的整形变量来控制Node数组的状态(类似的控制变量在线程池中也有使用)。
sizeCtl默认为0,构造函数中被设置为数组的初始容量,数组初始化过程中为-1,初始化完毕为扩容阈值,扩容过程中为 -(1+扩容线程数)。

ConcurrentHashMap的putVal方法

    final V putVal(K key, V value, boolean onlyIfAbsent) {
        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());
        int binCount = 0;
        //整个put操作自旋
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            //初始化Node数组
            if (tab == null || (n = tab.length) == 0)
                tab = initTable();
            //计算出的下标处无结点,CAS操作进行赋值
            else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
                if (casTabAt(tab, i, null,
                             new Node<K,V>(hash, key, value, null)))
                    break;                   // no lock when adding to empty bin
            }
            //如果当前下标处结点的hash为-1,则说明数组正在扩容,因为扩容过程中每处理完一个桶,都会
            //将原数组该桶的位置放入一个ForwardingNode结点,该节点hash写死为-1。此时需要协助扩容。
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                //此时说明该下标处有结点,直接把该结点锁住,相当于锁住了整个桶(以该节点为首的链表或树)。
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            binCount = 1;
                            for (Node<K,V> e = f;; ++binCount) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    oldVal = e.val;
                                    if (!onlyIfAbsent)
                                        e.val = value;
                                    break;
                                }
                                Node<K,V> pred = e;
                                if ((e = e.next) == null) {
                                    pred.next = new Node<K,V>(hash, key,
                                                              value, null);
                                    break;
                                }
                            }
                        }
                        else if (f instanceof TreeBin) {
                            Node<K,V> p;
                            binCount = 2;
                            if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
                                                           value)) != null) {
                                oldVal = p.val;
                                if (!onlyIfAbsent)
                                    p.val = value;
                            }
                        }
                    }
                }
                if (binCount != 0) {
                    if (binCount >= TREEIFY_THRESHOLD)
                        treeifyBin(tab, i);
                    if (oldVal != null)
                        return oldVal;
                    break;
                }
            }
        }
        //增加结点计数,可能涉及到并发修改、扩容、协助扩容等场景。
        addCount(1L, binCount);
        return null;
    }

扩容的核心方法transfer(迁移)

    private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) {
        int n = tab.length, stride;
        //确定扩容步长,最小步长为16,即将原数组从后往前每16个桶划分为一段,每个线程单次只负责一个分段的结点迁移。
        if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE)
            stride = MIN_TRANSFER_STRIDE; // subdivide range
        //首个负责扩容的线程初始化新数组,长度为原数组长度2倍
        if (nextTab == null) {            // initiating
            try {
                @SuppressWarnings("unchecked")
                Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1];
                nextTab = nt;
            } catch (Throwable ex) {      // try to cope with OOME
                sizeCtl = Integer.MAX_VALUE;
                return;
            }
            nextTable = nextTab;
            transferIndex = n;
        }
        int nextn = nextTab.length;
        ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab);
        boolean advance = true;
        boolean finishing = false; // to ensure sweep before committing nextTab
        for (int i = 0, bound = 0;;) {
            Node<K,V> f; int fh;
            while (advance) {
                int nextIndex, nextBound;
                //判断当前分段(比如线程分配到的16个桶)是否遍历完毕
                if (--i >= bound || finishing)
                    advance = false;
                //判断是否还有可以分配的区域
                else if ((nextIndex = transferIndex) <= 0) {
                    i = -1;
                    advance = false;
                }
                //线程通过CAS操作获取自己负责的分段,设置边界下标bound和用于循环的下标i
                else if (U.compareAndSwapInt
                         (this, TRANSFERINDEX, nextIndex,
                          nextBound = (nextIndex > stride ?
                                       nextIndex - stride : 0))) {
                    bound = nextBound;
                    i = nextIndex - 1;
                    advance = false;
                }
            }
            //判断扩容结束,即整个自旋操作的出口
            if (i < 0 || i >= n || i + n >= nextn) {
                int sc;
                if (finishing) {
                    nextTable = null;
                    table = nextTab;
                    sizeCtl = (n << 1) - (n >>> 1);
                    return;
                }
                if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) {
                    if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT)
                        return;
                    //最后一个扩容的线程将finishing改为true
                    finishing = advance = true;
                    i = n; // recheck before commit
                }
            }
            //如果元素组该桶是空的,直接替换为ForwardingNode结点,表示该桶处理完毕。
            else if ((f = tabAt(tab, i)) == null)
                advance = casTabAt(tab, i, null, fwd);
            else if ((fh = f.hash) == MOVED)
                advance = true; // already processed
            else {
            	//扩容操作需要锁住当前桶,即以当前下标结点为首的链表或红黑树。
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        Node<K,V> ln, hn;
                        if (fh >= 0) {
                            int runBit = fh & n;
                            Node<K,V> lastRun = f;
                            for (Node<K,V> p = f.next; p != null; p = p.next) {
                                int b = p.hash & n;
                                if (b != runBit) {
                                    runBit = b;
                                    lastRun = p;
                                }
                            }
                            if (runBit == 0) {
                                ln = lastRun;
                                hn = null;
                            }
                            else {
                                hn = lastRun;
                                ln = null;
                            }
                            for (Node<K,V> p = f; p != lastRun; p = p.next) {
                                int ph = p.hash; K pk = p.key; V pv = p.val;
                                if ((ph & n) == 0)
                                    ln = new Node<K,V>(ph, pk, pv, ln);
                                else
                                    hn = new Node<K,V>(ph, pk, pv, hn);
                            }
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                        else if (f instanceof TreeBin) {
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> lo = null, loTail = null;
                            TreeNode<K,V> hi = null, hiTail = null;
                            int lc = 0, hc = 0;
                            for (Node<K,V> e = t.first; e != null; e = e.next) {
                                int h = e.hash;
                                TreeNode<K,V> p = new TreeNode<K,V>
                                    (h, e.key, e.val, null, null);
                                if ((h & n) == 0) {
                                    if ((p.prev = loTail) == null)
                                        lo = p;
                                    else
                                        loTail.next = p;
                                    loTail = p;
                                    ++lc;
                                }
                                else {
                                    if ((p.prev = hiTail) == null)
                                        hi = p;
                                    else
                                        hiTail.next = p;
                                    hiTail = p;
                                    ++hc;
                                }
                            }
                            ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) :
                                (hc != 0) ? new TreeBin<K,V>(lo) : t;
                            hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) :
                                (lc != 0) ? new TreeBin<K,V>(hi) : t;
                            setTabAt(nextTab, i, ln);
                            setTabAt(nextTab, i + n, hn);
                            setTabAt(tab, i, fwd);
                            advance = true;
                        }
                    }
                }
            }
        }
    }

ConcurrentHashMap的get方法

    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode());
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (e = tabAt(tab, (n - 1) & h)) != null) {
            //key相同则直接返回
            if ((eh = e.hash) == h) {
                if ((ek = e.key) == key || (ek != null && key.equals(ek)))
                    return e.val;
            }
            //如果数组正在扩容,待当前桶扩容完毕后,调用ForwardingNode的find方法去新数组里找。
            else if (eh < 0)
                return (p = e.find(h, key)) != null ? p.val : null;
            //往下依次遍历
            while ((e = e.next) != null) {
                if (e.hash == h &&
                    ((ek = e.key) == key || (ek != null && key.equals(ek))))
                    return e.val;
            }
        }
        return null;
    }

参考资料:https://blog.csdn.net/qq_17555249/article/details/107855623

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值