HashMap源码学习

一、简介

HashMap ,是一种散列表,存储key-Value 键值对,又称哈希表。

二、字段属性

    //数组节点
    transient Node<K,V>[] table;
    //key value  的个数。表示使用的个数,
    transient int size;
    
    //遍历过程中修改的次数。
    transient int modCount;
    
    //扩容阈值
    int threshold;

    //扩容因子
    final float loadFactor;

HashMap底层是通过数组+链表,同时结合红黑树实现的。

三、构造方法

   //初始容量 并默认了一个扩容因子、
    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
    }

    /**
     * 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
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }


/**
 * 最大的容量为 2^30 。
 *
 * 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;

    public HashMap(int initialCapacity, float loadFactor) {
    // 校验 initialCapacity 参数
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " +
                                           initialCapacity);
    // 避免 initialCapacity 超过 MAXIMUM_CAPACITY
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    // 校验 loadFactor 参数
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                                           loadFactor);
    // 设置 loadFactor 属性
    this.loadFactor = loadFactor;
    // <X> 计算 threshold 阀值
    this.threshold = tableSizeFor(initialCapacity);
    }

四、哈希函数

    static final int hash(Object key) {
        int h;
        //key.hashCode()获取的是对象的哈希码值,是一个整数值, h>>>16 是位运算,向右移动16位,获得h的高位部分,
        // ^ 异或 , 也就是将他的高8位和低8位进行异或. 不进位相加.
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

hash 函数性能很高,因为他是基于位运算,同时能够保证足够的离散性,尽量保证hash冲突的概率最小。

五、添加单个元素

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)   //如果Node数组为null, node 数组的长度为0
            n = (tab = resize()).length;//实际上是在第一次插入数据的时候才分配的数组 ,在这里指定了初始容量,
        if ((p = tab[i = (n - 1) & hash]) == null)  // 这里的i 是通过(n-1) & hash ,其实他的效果等价于 hash % n (取的是余数),
            //结论就是: 对于n为2的次幂时 (n-1) & hash == hash % n ;
            // 可以这么理解一下hash % n 的值肯定小于n, 那么他的值是不是就由hash的后几位决定了, 同理(n-1) 肯定是一个奇数,类似于1111 & hash 也是由hash决定了,
            //解释的有点勉强,  结论就是这么个结论, 可以多验证几下. 另外 % (模运算) 底层也是位运算,所以直接位运算确 效率确实更快一些吧.
            tab[i] = newNode(hash, key, value, null);   //插入节点数据,
        else {
            //下面是节点如果存在元素, 也就是发生hash 冲突.
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //如果这个key 与头结点的key 相同.
                e = p;
            else if (p instanceof TreeNode) //如果这个key 与头结点不同,且头结点是树节点,红黑树
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                //下面就是链表结构.
                for (int binCount = 0; ; ++binCount) {
                    //(1) 依次从头结点开始next 判断下一个节点是否为null
                    if ((e = p.next) == null) {
                        //可以看出这里是尾插法 ,p.next == null 的时候才会插入.
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash); //此时链表节点有8个 ,然后判断hashmap的数组的长度是否 >= 64 ,超过了就替换成红黑树,否则就扩容
                        break;
                    }
                    //(2) 如果next 节点不为null,会去判断Node 节点的hash 值是否与 插入的hash值相等,key是否相等.相等就跳出循环.
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) //这里有一个问题,hashcode 码相等,但是key不一定相等.如果key相等,那么hashcode 一定得相等.
                        // HashMap 是根据hashcode 去寻找的下标的, 如果只重写equals 但是不重写 hashcode, 在这个地方就不会 执行break 了.会出现重复key (两个key是一样的,但是hashcode 不一样.)
                        break;
                    p = e; //不相等, 将p指向e
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                //put方法调用的时候, 这个onlyIfAbsent 为false ,所以会覆盖之前的值 , putIfAbsent 方法调用的时候这个 onlyIfAbsent 传的是true 不会覆盖之前的值.
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);//回调函数, Hashmap 中没有应用.
                return oldValue;
            }
        }
        ++modCount;
        //size (映射数量)  threshold 这个变量会在resize()  扩容的时候分配为 容量*扩容因子,
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//回调函数  Hashmap 中没有应用 evict
        return null;
    }

putIfAbsent(K key, V value) 方法,当 key 不存在的时候,添加 key-value 键值对到其中


//如果存在那么 , 那么不会覆盖之前的值,但是会返回old value , 不存在的才会添加,
@Override
public V putIfAbsent(K key, V value) {
    return putVal(hash(key), key, value, true, true);
}

六、扩容



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;
            }
            //扩容是按照两倍扩容的, (newCap = oldCap << 1)
            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;// 这里初始化了容量,如果初始化为7 ,那么oldThr就为8 ,  (2的整数次幂)
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;  //无参构造的时候默认容量就是 16
            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) {//这里e = oldTab[j] 是直接将oldtab[j]对象的值复制一份给了e, 并不是将对象的地址传给了e
                    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 节点记录的是扩容后仍然在该位置上的链表节点
                        Node<K,V> hiHead = null, hiTail = null;//这个记录的是扩容后在j + oldCap 上的链表节点.
                        Node<K,V> next;
                        //链表的处理
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {   //这块我也不太理解,但是确实就是这么个规律.....(e.hash & oldCap) == 0 说明它位置不会变,
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {                  //否则就会添加到j+oldCap 的位置
                                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;
    }

扩容 是按照两倍大小进行扩容, 并且Hashmap 是在第一次进行插入元素的时候进行分配数组容量的,如果没有指定容量,那么分配默认的容量DEFAULT_INITIAL_CAPACITY ==16 ,如果指定的容量那么会分配一个2的整数次幂大小的空间,

七、树化

#treeifyBin(Node<K,V>[] tab, int hash) 方法,将 hash 对应 table 位置的链表,转换成红黑树。代码如下:

/**
 * 每个位置链表树化成红黑树,需要的链表最小长度
 *
 * 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.
 */
static final int TREEIFY_THRESHOLD = 8;

/**
 * HashMap 允许树化最小 key-value 键值对数
 *
 * 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.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    // <1> 如果 table 容量小于 MIN_TREEIFY_CAPACITY(64) ,则选择扩容
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();
    // <2> 将 hash 对应位置进行树化
    else if ((e = tab[index = (n - 1) & hash]) != null) {
        // 顺序遍历链表,逐个转换成 TreeNode 节点
        TreeNode<K,V> hd = null, tl = null;
        do {
            TreeNode<K,V> p = replacementTreeNode(e, null);
            if (tl == null)
                hd = p;
            else {
                p.prev = tl;
                tl.next = p;
            }
            tl = p;
        } while ((e = e.next) != null);
        // 树化
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}



//为什么是 链表长度达到8会进行树化呢
 * Because TreeNodes are about twice the size of regular nodes, we
 * use them only when bins contain enough nodes to warrant use
 * (see TREEIFY_THRESHOLD). And when they become too small (due to
 * removal or resizing) they are converted back to plain bins.  In
 * usages with well-distributed user hashCodes, tree bins are
 * rarely used.  Ideally, under random hashCodes, the frequency of
 * nodes in bins follows a Poisson distribution
 * (http://en.wikipedia.org/wiki/Poisson_distribution) with a
 * parameter of about 0.5 on average for the default resizing
 * threshold of 0.75, although with a large variance because of
 * resizing granularity. Ignoring variance, the expected
 * occurrences of list size k are (exp(-0.5) * pow(0.5, k) /
 * factorial(k)). The first values are:
 *
 * 0:    0.60653066
 * 1:    0.30326533
 * 2:    0.07581633
 * 3:    0.01263606
 * 4:    0.00157952
 * 5:    0.00015795
 * 6:    0.00001316
 * 7:    0.00000094
 * 8:    0.00000006
 * more: less than 1 in ten million






// 当树的节点少等于于6那么会退化为链表,,
static final int UNTREEIFY_THRESHOLD = 6;

首先,参考泊松概率函数,当链表长度到达8的概率是0.00000006 千万分之一,所以绝大多数情况下,在hash算法正常的时候,不会出现链表转红黑树情况。

红黑树是一个自平衡二叉搜索树,自平衡特性,红黑树通过一系列规则确保了树的自平衡特性,从而保持树的高度相对比较小,插入和删除操作之后,需要根据红黑树的规则进行调整,以确保仍然满足红黑树的性质。

八、添加多个元素

putAll(Map<? extends K, ? extends V> m) 方法,添加多个元素到HashMap 中。代码如下:
 public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }
    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)
                    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);
            }
        }
    }

九、移除单个元素

   public V remove(Object key) {  //HashMap 只有扩容,没有缩容的机制。
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {//找到对应的node节点
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))//比较node节点hash值 是否相等,key 是否相等.
                node = p;
            else if ((e = p.next) != null) {//不相等的话比较下一个节点,如果下一个节点不是null
                if (p instanceof TreeNode) //是红黑树
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);//查找红黑树,然后比较
                else {
                    do {//链表结构
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;//如果匹配到了 跳出循环
                            break;
                        }
                        p = e;//这里保存的是前一个节点赋值给了p
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)//红黑树
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)//头结点就是这个key对应的node
                    tab[index] = node.next;
                else
                    p.next = node.next;//链表的话就是将p的下一个指针只想了node的下一个.
                // 修改数增加,
                ++modCount;
                // Hashmap的数量减少
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        //查不到 返回null
        return null;
    }

十、查询单个元素

get(Object key) 方法,查找单个元素。代码如下:

    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) { // 首先需要确保hashmap底层的数组Node 节点不为null, 长度大于0,然后根据hash值与数组长度取模运算获取到node节点
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))  //如果在这里之重写equals 方法,而没有重写hashcode方法, 可能就获取不到原来key的对象
                // (比如我现在有一个key :A 还有一个Key :B  现在A.equals(B) == true 成立,  但是A.hashcode == B.hashcode 不成立 ,我想要通过key B 获取到key A ,对应的value ,这时候就不存在了)
                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);
            }
        }
        //没有的话,就返回null
        return null;
    }

十一、转换程Set/Collection

public Set<K> keySet() {
    Set<K> ks = keySet; //获取缓存
  if (ks == null) {//如果不存在 ,则创建。
      ks = new KeySet();
      keySet = ks;
     }
    return ks;
}

    // AbstractMap.java
transient Collection<V> values;

// HashMap.java
public Collection<V> values() {
    // 获得 vs 缓存
    Collection<V> vs = values;
    // 如果不存在,则进行创建
    if (vs == null) {
        vs = new Values();
        values = vs;
    }
    return vs;
}

transient Set<Map.Entry<K,V>> entrySet;

public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    // 获得 entrySet 缓存
    // 如果不存在,则进行创建
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

十二、清空


public void clear() {
    Node<K,V>[] tab;
    // 增加修改次数
    modCount++;
    if ((tab = table) != null && size > 0) {
        // 设置大小为 0
        size = 0;
        // 设置每个位置为 null
        for (int i = 0; i < tab.length; ++i)
            tab[i] = null;
    }
}

总结:

HashMap 是一种散列表结构,底层采用数组+链表+红黑树来实现存储。

HashMap 默认的大小是 16,只有在第一次插入元素的时候才会分配空间,并且分配的大小一定是二的整数次幂。

HashMap扩容的时候,节点位置需要重新计算,(位置要不不变,要不在原位置+上个桶的长度的)

HashMap是一个槽一个槽进行计算的(e.hash & oldCap ==0 说明位置没有变,否则移到下一个位置)。

HashMap 默认加载因子是0.75,可以指定初始大小,并分配初始加载因子。

HashMap 链表树化为红黑树,需要满足两个条件: HashMap 的table 数组长度大于等于64 ,其次槽位的链表长度大于等于8。

这个阈值8 是因为,参考泊松分布概率函数,达到8次的Hash碰撞的概率不足千万分之一。

当树节点小于等于6时,会退化回链表。

Hashmap的查找和添加键值对的平均时间复杂度为O(1)。

对于槽位是链表节点,平均复杂度为O(K) 。其中K为链表长度。

对于槽位是红黑树的节点,平均复杂度为O(logk),其中K为树的节点数量。

最重要的我认为是Hash函数:

计算key的hashcode返回32的int整数,然后高16位和低16位异或返回hash值( 保证更加离散 )

HashMap 在1.7采用的是头插法,在1.8 采用的尾插法,提高了便利的效率,新插入的元素一般都在后面。

HashMap 是非线程安全的,因此在多线程环境下,是会出现数据覆盖,链表成环,,但是大多数我们的场景中HashMap是够用了的。

Hashtable 是线程安全的,源码中对每个方法加了一个synchronzied 锁,保证了同一时刻只有一个线程操作它,但是降低了并发度。

并发环境下用ConcurrentHashMap  ,性能更好。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值