HashMap源码解析

学习指南:

1、HashMap构造函数

2、HashMap底层数据结构

3、HashMap方法深入解析

HashMap构造函数

HashMap提供四个构造函数,前面三个可以看做是一样的,都是创建集合时指定初识容量和负载因子;

/**
     * 构造一个指定初识容量和负载因子的空集合
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     */
    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);
    }

   /**
     * 构造一个指定初识容量和默认负载因子的空集合
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

   /**
     * 构造一个默认初始化容量和默认负载因子的空集合
     * 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
    }

第四个构造函数给定了一个集合,即新创建的集合的负载因子为默认大小(0.75F),并且需要把给定集合的元素放入新集合中;

   /**
     * 构造一个新集合,匹配指定集合中的元素,并设置默认负载因子
     * Constructs a new <tt>HashMap</tt> with the same mappings as the
     * specified <tt>Map</tt>.  The <tt>HashMap</tt> is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified <tt>Map</tt>.
     * @param   m the map whose mappings are to be placed in this map
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        // 默认负载因子
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

   /**
     * 该方法用于两个地方,其一是构造方法,其二是集合方法putAll()
     * 在构造方法中调用时,evict参数为false,其他调用为true
     * Implements Map.putAll and Map constructor
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                // 下面两个步骤应该是计算指定集合的元素个数所需要的最小容量
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    // 如果所需的最小容量比默认容量大,则把容量更新为最小容量,
                    // 并进行位计算把值调整为2的幂次方
                    threshold = tableSizeFor(t);
            }
            else if (s > threshold)
                // 如果元素个数依然大于当前阈值,则进行集合扩容
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                // 遍历把元素添加到创建的集合中
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

HashMap的底层数据结构

首先来看下在HashMap中是怎么存放元素的呢?

HashMap底层存储元素的对象:class Node<K, V> implements Map.Entry<K, V>

   /**
     * 底层节点元素
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;    // key的hash计算值
        final K key;       // key值
        V value;           // 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;
        }

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

JDK8中HashMap的底层数据结构是:数组+链表+红黑树

先来看下类中定义的部分静态常量

 

DEFAULT_INITIAL_CAPACITY(默认容量大小 - 16)

MAXIMUM_CAPACITY(最大容量 - 2)

DEFAULT_LOAD_FACTOR(负载因子 - 0.75f)

TREEIFY_THRESHOLD(由链表转化为红黑树的最小元素个数,即当冲突元素个数达到8时,转化为红黑树)

UNTREEIFY_THRESHOLD(冲突元素减少到6时,重新切换回链表)

MIN_TREEIFY_CAPACITY(转化为红黑树的最小容量)

链表树化的条件:底层数组的容量大于等于64(MIN_TREEIFY_CAPACITY)且有其中一个链表的元素个数超过8个(冲突元素个数大于等于8)

   /**
     * 默认容量大小
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

   /**
     * 最大容量大小,且容量大小一定是2的幂次方
     * 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;

   /**
     * 默认负载因子
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

   /**
     * 由链表转化为红黑树的区分值(当链表元素个数增长到8时转化为红黑树)
     */
    static final int TREEIFY_THRESHOLD = 8;

   /**
     * 当冲突元素减少到6个时,由红黑树切换为链表
     */
    static final int UNTREEIFY_THRESHOLD = 6;

   /**
     * 链表转化成红黑树的最小容量
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

总结:当向集合中添加元素时,会先根据key的(hash值和容量长度减一进行与计算)确定元素在桶数组中的位置,如果该位置不存在元素,则直接插入即可;如果该位置已经存在元素了(hash冲突),再根据key的equals方法判断是否相等,如果相等,则更新该位置元素值,如果不相等,则用已存在元素的节点对象中的Node.next存放新添加的元素;当桶数组长度超过64并且有其中一个链表的长度超过8时,则会由链表转化为红黑树,如果元素个数小于6了,则又会转换成链表;

HashMap方法解析

hash值计算方法:

向集合中添加一个元素时,先通过该方法计算出hash值,然后和集合长度减一进行与计算,得到元素在桶中的位置所在;

    /**
      * 计算key的hash值
      * key的hashcode值与高16位进行异或运算,提高散列性
      */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

resize扩容方法:

   /**
     * 扩容
     * @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;
    }

put插入元素方法:

   /**
     * 元素插入
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

   /**
     * 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;
        
        // 如果桶数组为空,则先初始化,即扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

        // 如果通过hash计算得到该数组中桶的位置元素为空,则直接放入该位置
        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;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

get获取元素方法:

   /**
     * 获取指定key值的元素值
     * @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;
        
        // 如果节点数组为空,长度大于0且通过hash计算得到桶位置的元素不为空的情况
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {

            // 如果数组中该桶位置的元素hash值相等且equals值比较也相等,则直接返回该元素
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;

            // 如果该节点是一个链表,则先判断是否是树节点,如果是则用红黑树的获取元素方法,
            // 如果不是则遍历链表,知道找到一个元素的hash值相等且equals比较也相等
            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;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值