java.util.HashMap jdk1.8下的源码分析

本文详细解析了HashMap在JDK1.8中的源码实现,包括类结构、初始化参数、常用方法如put、get、replace和remove的解析,以及扩容机制。同时,指出了多线程环境下可能出现的环状链表问题和频繁扩容的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文基于jdk1.8 主要以源码视角进行分析,解析代码的实现以及其中可能存在误用的地方.

HashMap: 哈希散列表,以key-value键值对形式存在,无序,查找的时间维度与空间维度均为O(1).能够让我们快速对一些数据进行快速的归集.

1. 类结构,见下图:

在这里插入图片描述

初始化参数

默认初始容量为16,采用二进制位移. 等同于java中Math.pow(2, 4);

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

最大容量为2的30次方,如果初始化或者扩容时大于该值则取2的30次方, 等同于java中Math.pow(2, 30);

 static final int MAXIMUM_CAPACITY = 1 << 30;

默认负载因子,当使用中容量达到当前容量*0.75f时,进行扩容,可看做预扩容机制

static final float DEFAULT_LOAD_FACTOR = 0.75f;

转红黑树阈值,当达到该阈值时链表转换为红黑树,主要是优化,减少查询的链路

static final int TREEIFY_THRESHOLD = 8;

转node阈值,当当前桶的存储为红黑树时,其红黑树节点小于此阈值转回node数据结构,应该小于 TREEIFY_THRESHOLD 阈值.两者如果冲突可能导致转换为红黑树后再添加元素会转回node结构.

static final int UNTREEIFY_THRESHOLD = 6;

定义的默认最小红黑树容量,一般设置为 TREEIFY_THRESHOLD * 4 ,减少频繁的扩容,因为红黑树也是有初始容量的.

static final int MIN_TREEIFY_CAPACITY = 64;

定义的内部类,单向链表结构.当前对象包含下一对象的引用.用于存储桶中数据

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
// .....

}

数据集

transient Node<K,V>[] table;```

键值对的集合
```java
t`ransient Set<Map.Entry<K,V>> entrySet;`

当前散列表的键值对映射数量

transient int size;

对当前散列表结构修改的次数

transient int modCount;

容量

int threshold;

负载因子

final float loadFactor;

2 部分常用方法解析

2.1 初始化方法
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);
    }

如果初始化时,传入用户自定义的初始容量以及负载因子时,合法性校验,初始化容量不能小于0,如果初始化容量大于允许的最大容量即230时,则取230.如果负载因子 小于等于0或者非数字,异常返回. 无参构造器取的都是默认负载因子以及容量.

2.2 put方法
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
    // 取key值的hash,通过key的hashCode方法后,取高16位与低16位取位异或运算
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    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)
            // 如果散列表为null或者容量为0,则调用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))))
                // 已经存在,判断key值是否相等,value是否相等,存在则放入e中
                e = p;
            else if (p instanceof TreeNode)
                // 不相等时,判断是否为红黑树结构,如果是则进行红黑树插入
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                // 为node结构时
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        // 如果链表下一元素不存在,则插入
                        p.next = newNode(hash, key, value, null);
                        // 判断元素数量是否已经达到转红黑树阈值,达到则进行node转红黑树
                        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
                // 插入的键值已经存在,onlyIfAbsent 在put时传入false,此处就忽略.当之前存在的键值对 值为空时,将新的值赋值
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 尾部插入当前元素
                afterNodeAccess(e);
                return oldValue;
            }
        }
        // 结构变化记录+1
        ++modCount;
        if (++size > threshold)
            // 如果当前长度超过设置长度,进行扩容
            resize();
        afterNodeInsertion(evict);
        return null;
    }
2.3 get方法
 public V get(Object key) {
        Node<K,V> e;
        // hash方法与put相同
        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;
        // 通过key值hash与数组长度取位与运算拿到桶下标,然后first赋值
        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 {
                    // 通过循环取下一个元素进行查找,最大查找次数为7
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
2.4 replace方法
@Override
public boolean replace(K key, V oldValue, V newValue) {
    Node<K,V> e; V v;
    // 通过getNode获取到指定key的元素,然后进行判断是否等于oldValue,如果等于进行修改操作.不满足则放弃,cas的一种实现
    if ((e = getNode(hash(key), key)) != null &&
        ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
        e.value = newValue;
        afterNodeAccess(e);
        return true;
    }
    return false;
}
2.5 remove方法
  public V remove(Object key) {
        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<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != 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;
                    } 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)
                    // 如果为头部元素,则设置为头部的下一个元素为头部元素
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

3 扩容机制

  final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // cap为数组容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            // 如果数组的长度已经达到设置的默认最大,则将元素总量的长度设置为int最大值
            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
        }
        // 如果原来的负载因子大于0,则进行赋值
        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时会进行检查,当前容量是否达到扩容阈值,此处阈值为Capacity * loadFactor,扩容机制为左位移一位,即两倍扩容,初始16.

4 存在问题

在进行扩容的时候如果多线程访问会引发环状链表,如果查询一个不存在的值,则会一直处于循环中,形成死循环.

在大量数据插入,未设置足够大的初始容量时会引发频繁扩容,而每次扩容会对之前的数据进行重新写入,极为耗时且占用内存.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值