HashMap

作者: 神的漾 | 来源:发表于2020-11-17 20:06 被阅读0次

    1.HashMap简介

    HashMap是基于哈希表的Map接口实现,是以key-value存储数据.除了不是同步的和允许使用null以外,HashMap和HashTable大致相同.如果想使HashMap同步,可以使用Collections.synchronizedMap(Map)使HashMap具有同步能力,或者使用ConcurrentHashMap本身就具有同步的能力.
    HashMap的实现不是同步的,所以是线程不安全的,它的key,value都可以为null.此外在JDK1.8中,HashMap是由数组+链表+红黑树构成的,新增了红黑树作为底层数据结构,结构变复杂了,但是效率也变的更高效了.
    当一个值中要存储到Map的时候会根据Key的值来计算出他的hash,通过hash来确认到数组的位置,如果发生哈希碰撞,就以链表的形式存储,如果链表长度超过8时,HashMap就会把这个链表转换成红黑树来存储.因为链表很短的时候,即使遍历,速度也非常快,但是当链表长度不断变长,肯定会对查询性能有一定的影响.所以转成红黑树.每次resize会把HashMap的size扩大一倍.
    树形化时会判断是否大于MIN_TREEIFY_CAPACITY大于才会树形化,小于的话会直接扩容.

    数据结构

    HashMap数据结构

    上面是HashMap的数据结构.当一个值要存储到Map的时候会根据Key的值来计算出他的Hash值,通Hash值来确认到数组的位置,如果发生哈希碰撞就以链表的形式存储,如果链表长度超过8,就会把这个链表置换成红黑树来存储.

    类结构

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

    是继承了AbstractMap<K,V>和实现Map<K,V>,Cloneable,Serializable
    AbstactMap已经实现了Map,据java集合框架创始人josh Bloch描述,继承map的写法是一个失误.

    • CloneAble 空接口,表示可以克隆
    • Serializable 序列化
    • AbstractMap 提供Map实现接口

    属性意义

    /**
         * The default initial capacity - MUST be a power of two.
         *   默认初始容量,必须是2的n次方,默认是16,1向右移4位就是2的4次幂
         */
        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.
         * 最大容量 2的30次幂,值为1 073 741 824,这么写简单,运算效率也高.
         */
        static final int MAXIMUM_CAPACITY = 1 << 30;
    
        /**
         * The load factor used when none specified in constructor.
         * 默认加载因子.0.75
         */
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
        /**
         * The bin count threshold for using a tree rather than list for a
         * bin.  Bins are converted to trees when adding an element to a
         * bin with at least this many nodes. The value must be greater
         * than 2 and should be at least 8 to mesh with assumptions in
         * tree removal about conversion back to plain bins upon
         * shrinkage.
         * 树形化阀值值=8,要大于2并至少是8,使整个链表转化为红黑树.
         */
        static final int TREEIFY_THRESHOLD = 8;
    
        /**
         * The bin count threshold for untreeifying a (split) bin during a
         * resize operation. Should be less than TREEIFY_THRESHOLD, and at
         * most 6 to mesh with shrinkage detection under removal.
         * 取消树形化阀值 =6,要小于TREEIFY_THRESHOLD,
         * 指从黑红树转换为链表的阀值
         */
        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.
         * 最小树形化阀值,当hash表中容量大于该值时才进行树形化.
         * 否则直接扩容.为了避免扩容和树形化冲突,
         * 这个值不能小于4 * TREEIFY_THRESHOLD
         */
        static final int MIN_TREEIFY_CAPACITY = 64;
    

    变量意义

    /**
         * 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.)
         * ransient代表序列化时不会存储
         * 数组表,第一次使用时初始化,并调整为必要的大小,长度总是2的n次幂.
         * 某些情况也允许长度为0的.
         */
        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.
         * HashMap中存储数据的数量
         */
        transient int size;
    
        /**
         * The number of times this HashMap has been structurally modified
         * Structural modifications are those that change the number of mappings in
         * the HashMap or otherwise modify its internal structure (e.g.,
         * rehash).  This field is used to make iterators on Collection-views of
         * the HashMap fail-fast.  (See ConcurrentModificationException).
         * 用来记录HashMap的修改次数.
         */
        transient int modCount;
    
        /**
         * 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.)
        // 要调整大小的下一个大小值(容量*负载因子)
        int threshold;
    
        /**
         * The load factor for the hash table.
         *
         * @serial
         * 哈希表负载因子
         */
        final float loadFactor;
    

    构造方法

    put方法

    /**
         * Associates the specified value with the specified key in this map.
         * If the map previously contained a mapping for the key, the old
         * value is replaced.
         *
         * @param key key with which the specified value is to be associated
         * @param value value to be associated with the specified key
         * @return the previous value associated with <tt>key</tt>, or
         *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
         *         (A <tt>null</tt> return can also indicate that the map
         *         previously associated <tt>null</tt> with <tt>key</tt>.)
         * 将此映射中的指定值与指定键关联.如果以前的映射包含键的映射,则旧的值被          
         * 替换.
         * return 会返回旧的关联的键值,,如果无映射值,会返回null,也有可能是原键值映                
         * 射的就是null值.
         */
        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    

    put方法实际调用的是putVal方法来进入数据插入,这里调用了hash(key)方法,来看看hash方法如何实现的.

     /**
         * Computes key.hashCode() and spreads (XORs) higher bits of hash
         * to lower.  Because the table uses power-of-two masking, sets of
         * hashes that vary only in bits above the current mask will
         * always collide. (Among known examples are sets of Float keys
         * holding consecutive whole numbers in small tables.)  So we
         * apply a transform that spreads the impact of higher bits
         * downward. There is a tradeoff between speed, utility, and
         * quality of bit-spreading. Because many common sets of hashes
         * are already reasonably distributed (so don't benefit from
         * spreading), and because we use trees to handle large sets of
         * collisions in bins, we just XOR some shifted bits in the
         * cheapest possible way to reduce systematic lossage, as well as
         * to incorporate impact of the highest bits that would otherwise
         * never be used in index calculations because of table bounds.
         */
        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    

    可以看出HashMap是支持key为null的当key的值等于null的时候hash值返回0,HashTable是直接用key来获取HashCode,所以key为空会抛异常.
    首先计算出key的hashCode为h,然后与h无条件右移16位的二进制进行按位异或(^)得到最终的hash值.
    下面看下putVal方法的具体实现.

    /**
         * Implements Map.put and related methods
         * 实现了map的put和相关方法
         * @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是空或者长度为0,如果是就进行初始化.
            // 这里resize方法只是进行初始化实际并没有分配空间,所以在这里调用进行空间分配
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
           // 对hashcode进行取模运算,
           // i = (n - 1) & hash;这里i的值就是获取到值的位置. 如果tab[i] 为null就新增一个元素. 
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
               // 如果tab[i] 不等于空表示这个位置已经有值了.
                Node<K,V> e; K k;
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                  // 如果key的值已经存在,直接去替换已有值.
                    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) {
                            // 节点的最后一位的标志就是next值为null
                            p.next = newNode(hash, key, value, null);
                            // 判断节点的长度大于等于TREEIFY_THRESHOLD红黑树的阀值,就转换红黑树.
                            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;
            // 判断当前元素数量是否超过threshhold阀值,如果超过调用resize()
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
        }
    

    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) {
                if (oldCap >= MAXIMUM_CAPACITY) {
                    threshold = Integer.MAX_VALUE;
                    return oldTab;
                }
                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;
                        if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
                        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;
            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

          本文链接:https://www.haomeiwen.com/subject/hqtmbktx.html