Java 集合 HashMap 源码浅析

HashMap 的底层数据结构是什么?
/**
 * 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;
    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;
    }
    ......

我们跟进看看 Entry 是什么?

 /**
  * A map entry (key-value pair).
  */
interface Entry<K,V> {

...... // 省略方法定义

}

这一个个的 Node 是如何排列的呢?

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

显而易见, HashMap 的键值对一通过一个个的 Entry 对来保存的, 实现类 Node 是一个链表节点, 底层排列方式为数组, 数组中的每一个元素都是一个链表的头结点.



HashMap的初始容量是多少?
/**
 * The default initial capacity - MUST be a power of two.
 */
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16


哪些因素对 HashMap 的性能有较大影响?

我么知道 HashMap 是基于散列函数的,最坏的散列情况为线性的链表, 因此我们可以知道 如下这几点会极大的影响 HashMap 的性能:

  • 散列函数, 一个较好的散列函数应该能够均匀的分布 key 的位置.
  • 负载因子, 默认的负载因子为 0.75.
  • HashMap 中空筒位的数量, 空筒位越少, 冲突的可能性也就越大.


HashMap 是如何解决 hash 冲突的?

在JDK 1.7 中, HashMap 是用线性链表来维持冲突的, 而 jdk 1.8 中使用了二叉查找树中的红黑树, 解决了当冲突过多, 线性检索链表效率过低的情况.


HashMap 中新增的红黑树数据结构.
/**
 * 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);
    }

更多详细介绍: Java8 HashMap 深入理解




HashMap 是如何扩容的? 每次扩容多大? 什么时候扩容?

扩容过程源码:

    /**
     * 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;  // 第一次添加值是 oldTab 为 null, 因此会跳转至注释 1 处, 如果不是第一次添加值而导致的扩容, 会进入后面的循环.
        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  // ---------------- 2
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;    // -------------- 1
            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) {  // 如果 oldTab 不为 null, 说明不是第一次添加值.
            for (int j = 0; j < oldCap; ++j) {  // 大致的过程为循环取出 oldTab 中的每一个节点, 进行再 hash 复制到新的 tab 中的筒位中去, 由于 jdk 8 中添加了 红黑树的节点, 因此还要特殊处理红黑树.
                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;
    }

从上面源码 注释 2 处中我们可以看出, HashMap 每次扩容都会将原始容量乘以2, 即 HashMap 的容量永远都为 2 的整数次幂.

也许会有人好奇, 如果我们在构造函数中传入的初始容量不是 2 的整数次幂呢, 比如 9, 从源码中得出结果:

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
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);  //  ------- 1
}



/**
 * Returns a power of two size for the given target capacity.
 */
static final int tableSizeFor(int cap) {
    int n = cap - 1;
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}

进行了一系列的移位操作, 最终总是会把我们的值转换成一个比我们输入的值大的且是最近的 2 的整数次幂的值, 不信你去打断点, 或者反射拿出来调调 (嘿嘿).


至于何时扩容, 从 put 方法中找到线索:

/**
 * Implements Map.put and related metho
 *
 */
final V putVal(int hash, K key, V value
               boolean evict) {
    ....... 省略put的操作逻辑.
    ++modCount;
    if (++size > threshold)  // 重点在这一行.
        resize();
    afterNodeInsertion(evict);
    return null;
}

在每次 put 完后, 会判断 size(元素的个数) 是否大于 threshold(负载数, 等于负载因子*筒位数量), 如果大于则进行再 hash 扩容.



最后我们可以想到, 如果我们事先就能大概估计出 HashMap 中要存储多少个元素, 传入其容量, 就可以避免自动扩容而导致的再 hash 机制, 这也是提高 HashMap 效率的一种手段.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值