浅析HashMap

基于数组的ArrayList长于按索引获取对应元素,而在中间位置插入和删除元素,都涉及了对数组整体的移动、复制等操作,相比于链表的插入删除来说代价比较大。基于链表的LinkedList长于随机插入删除,Java的双向链表(LinekdList)只能从头到尾或者从尾到头遍历链表获取元素,相较于ArrayList也是比较慢的。那么有没有一种折中的解决方案,使得插入删除和取元素都比较便捷呢?我认为HashMap可以算是这么一种折中的解决方案。

HashMap概述

HashMap是一个实现了Map接口的哈希表,允许使用null值和null键。除了非同步和允许使用null之外,HashMap类与Hashtable大致相同。HashMap不保证映射的顺序,不保证该顺序恒久不变。

HashMap不是线程安全的,如果想要使用线程安全的HashMap,可以通以下代码来得到:

Map map = Collections.synchronizedMap(new HashMap());
复制代码

源码实现

HashMap在实现上采用了类似“链表的数组”这种数据结构,也有将之称为“拉链法”的,实现方式如图。

当HashMap根据key计算的hash值一样时,就发生了碰撞,这时就会根据如图所示的结构存储存储对应的对象。而这种碰撞发生非常多的话,那么HashMap读取对象的速度就会变慢。在java 8之后,如果一个“桶”的记录过大(TREEIFY_THRESHOLD = 8),HashMap会动态的使用一个专门的treemap实现来替换它。这样可以降低频繁发生碰撞时读对象的时间复杂度,当然,这需要你插入的key实现了Comparable接口,否则这样的优化是你享受不到的~

    // 单向链表的数据结构
    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; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        // 复写equal方法
        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
复制代码

重要的属性:

    /**
     * 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;

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

    /**
     * The next size value at which to resize (capacity * load factor).
     *
     * @serial
     */
    // (The javadoc description is true upon serialization.
    // Additionally, if the table array has not been allocated, this
    // field holds the initial array capacity, or zero signifying
    // DEFAULT_INITIAL_CAPACITY.)
    // 当实际大小超过此值时,会进行扩容 threshold = 容量 * 加载因子
    int threshold;

    /**
     * The load factor for the hash table.
     *
     * @serial
     */
    // 哈希表的加载因子,加载因子在这种实现方式中是数组被填充的程度,哈希表
    // 填充的越满,发生冲突的机会越大。在Java的实现中默认的加载因子是0.75
    final float loadFactor;
复制代码

接下来看一下HashMap默认的无参构造函数,看一下HashMap是如何初始化的:

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
复制代码

根据注释来看说是用默认的初始化容量(16)和默认的加载因子(0.75)来构造一个空的哈希Map。虽然注释是这么说的,但是并没有看到其他的动作,特别是上面提到的table这个数组,在构造函数中没有初始化的动作,其实他是在插入元素的时候才真正的初始化这个数组。来看一下我们平时调用的map.put(key,value)是如何实现的:

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
复制代码

具体的实现是putVal,那么看下这个方法:

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    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为空
        if ((tab = table) == null || (n = tab.length) == 0)
            // 事实上调用了resize(),初始化的动作就是在resize方法中完成的
            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;
            // HashMap如果频繁的发生碰撞,那么速度就会变慢,在java8 之后
            // 如果同一个索引频繁的发生碰撞,那么就会将这个索引底下的链表
            // 转换为红黑树,提升搜索的速度。很好,很牛逼的改进!
            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;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
复制代码

以上简单的看了下HashMap是如何插入一个值的,在计算索引上,HashMap并没有采用我们平时的哈希值对数组长度取余。而是采用了效率比较高的 & 运算,h & (length - 1),在注释中也说了,哈希表的长度必须是2的次幂,这么做的好处是什么呢?首先是h & (length - 1),length是2的次幂,那么length - 1用二进制表示的话必定全是1,而采用&运算的话,无论是0或1和1进行&运算,其结果既可能是0,也可能是1,这样就保证了运算后的均匀性。

在以上的注释中也提到了对table的初始化是在resize方法中完成的,那么看看resize方法:

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    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) {
            // 如果oldCap已经为最大容量
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 每次扩容是之前的2倍,一直是2的次幂
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        // 重新创建table数组,原数组为空,oldThr不为空
        // 扩展为oldThr大小
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        // 原数组为空,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;
                    // 桶中只有一个元素
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    // 如果第一个节点是TreeNode
                    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;
                            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;
    }
复制代码

接下来再看一下get方法是如何获取到值得

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        // hash & (length - 1)得到红黑树的树根或者是链表头
        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;
    }
复制代码

浅析暂时就到这了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值