面向java--HashMap

本文详细解析了Java8中HashMap的底层结构、源码分析、线程安全等问题,包括其数组+链表+红黑树的数据结构,构造方法、put、get、resize等核心方法的实现原理。

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

本文基于jdk1.8

一.底层结构

HashMap 底层在jdk8中采用数组+链表+红黑树的结构,大致如图:
在这里插入图片描述

通过Node类来实现链表结构

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
		......
		
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

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

这里为什么要重写hashCode和equals方法呢?

1.hashCode保证相同对象返回相同的值
2.equals是为了保证数据值相等,由于数据在同一链表中hashCode一致时无法区分

通过TreeNode类来实现树结构

	static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
	    // 父节点
        TreeNode<K,V> parent;  
        // 左子树
        TreeNode<K,V> left;
        // 右子树
        TreeNode<K,V> right;
        // 上一个节点数
        TreeNode<K,V> prev;
        // 表示当前节点颜色   
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

二.源码分析

1. 基本属性

	//  默认数组容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    // 最大的数组容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
	// 默认加载因子,设置0.75是由于理想均匀分布情况下,根据泊松分布,链表中出现7个元素几率为 0.00000094
	// 出现8个元素几率为0.00000006
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
	// 树化阈值,大于等于该值,进行是否树化判断
    static final int TREEIFY_THRESHOLD = 8;
	// 反树化阈值,小于的等于该值时,进行判断是否转为链表结构
    static final int UNTREEIFY_THRESHOLD = 6;
	// 最小树化容量,当元素个数大于等于该值,进行树化否则进行数组扩容
    static final int MIN_TREEIFY_CAPACITY = 64;
    // 保存数据数组,亦可成为桶
   transient Node<K,V>[] table;
    // 容量
    transient int size;
    // 阈值,用于判断是否应进行扩容
    int threshold;
 	// 加载因子
    final float loadFactor;

2. 构造方法

	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;
        // tableSizeFor返回大于等于给定容量的2的倍数的值
        this.threshold = tableSizeFor(initialCapacity);
    }
    /**
     * 推荐方式
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; 
    }

阿里规范推荐指定初始容量的方式.至于加载因子(loadFactor)一般使用默认的就可以了.
接着看构造函数中的 tableSizeFor方法

	/**
     * 返回一个大于或等于给定容量最接近2倍幂的数,如cap=5返回8,cap=25,返回32
     */
    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;
    }
以cap=9举例,
cap-1         1000
n |= n >>> 1  0100
			  1100
n |= n >>> 2  0011
			  1111
n |= n >>> 4  0000
			  1111	
n |= n >>> 8  0000
			  1111	
n |= n >>> 16 0000
			  1111
n + 1		 10000	 
10000 对应十进制为16正好符合 				  			  			  	

这里为何要cap - 1呢?
主要是防止当cap本身已是2的幂次的情况,例如cap=8 当不减1时,返回的是16显示不符合.
容量为何要2的幂次?
1.位运算比算数运算效率高,例如计算索引时
2.2的幂次,length-1的值都是1,此时索引的值等于hash的后几位,此时hashCode值是均匀分布的,结果就是均匀分布的

3. put方法

先看put方法,这里调用hash方法,获取数据在数组中的index位置

	static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
	public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

为什么要(h = key.hashCode()) ^ (h >>> 16),而不是直接key.hashCode()?
这是HashMap的巧妙之处,通过加入hashCode的高16参与计算,可以加大低位的随机性,降低hash碰撞几率.
接着看putVal方法

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 首次调用put方法,进行初始化
        if ((tab = table) == null || (n = tab.length) == 0)
        	// resize()初始化桶或扩容桶长度2倍的方法
            n = (tab = resize()).length;
        // (n - 1) & 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) //
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 查找到节点退出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 替换旧值
            if (e != null) { 
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 桶容量大于阈值,进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

afterNodeAccess 和afterNodeInsertion在此处是空方法,可以自行扩展.

4. resize方法

扩容方法是比较重要的方法,HashMap中的扩容分为两部分,一部是初始化,另一部是进行容量2倍扩容.

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;
            }
            // 进行2倍扩容   
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; 
        }
        else if (oldThr > 0) // 指定容量初始化
            newCap = oldThr;
        else { // 无参初始化
            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 { // 链表节点操作
                    	// 0位至oldTab.length-1位为低位,原低位头节点loHead,低位尾节点loTail 
                        Node<K,V> loHead = null, loTail = null;
                        // oldTab.length位至newCap-1位为高位,高位头节点hiHead ,高位尾节点hiTail 
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            // (e.hash & oldCap) == 0表示之前hash是处于低位,扩容是不影响的,
                            // 比如 之前为容量16,二进制10000,数值为3,二进制011,索引是3,扩容为32,二进制位100000,发现容量16,32低位其实没变化.
                            // 再比如数值19,索引还是3,二进制10011,(e.hash & oldCap) != 0,扩容之后为19,索引正好差了一个旧容量16的长度
                            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;
    }

为何java8中使用尾插?
如果使用头插,在扩容时,可能导致相互引用,形成死链.

5. treeifyBin方法

treeifyBin方法是将链表节点转为树节点

	final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 实际容量小于MIN_TREEIFY_CAPACITY 进行扩容而非树化
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
               // replacementTreeNode方法节点转化为树节点
                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);
        }
    }

6. treeify方法

treeify方法是一个实际实现构建树的方法

	final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                // 设置当前调用节点为根节点
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        // 当前节点hash与父子点hash比较,确定是左节点还是右节点
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        // 二者hash一致,指定key没有实现comparable接口
                 		// 或者实现了comparable接口并且和当前节点的键对象比较之后相等 
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            // 把两个key的object的hashcode()方法生成的hashcode比较决定方向    
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            // 平衡红黑树的操作
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            // 确保给的根节点是第一个节点
            moveRootToFront(tab, root);
        }

7. putTreeVal方法

putTreeVa方法,整体流程是先查找根节点,从根节点查找,存在该节点返回;否则创建插入新节点

	final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            // 获取根节点
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                // 父节点与当前节点hash比较查找
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                // 二者hash一致,key不为null且一致,查找到直接返回该节点    
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                 // 二者hash一致,指定key没有实现comparable接口
                 // 或者实现了comparable接口并且和当前节点的键对象比较之后相等         
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        // 递归遍历对比,看是否能够得到那个键对象equals相等的节点
						// 如果得到了键的equals相等的的节点就返回
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    // 把两个key的object的hashcode()方法生成的hashcode比较决定方向
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                // 根据方向,创建新节点并挂载到该节点的左子树或右子树上
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    // 设置新节点的前节点和后节点均为当前节点
                    x.parent = x.prev = xp;
                    // 原来节点的next不为空,则将这个next指向新节点
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                     // 平衡树,确保给的根节点是第一个节点    
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

8. get方法

get方法实际调用getNode获取节点信息,相较put方法较为简单

 	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) {
            // 头结点正好为查找的节点直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            // 存在后续节点,则继续查找,否则返回null    
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                	// 实际还是使用find递归方法查询节点 
                    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;
    }

9. remove方法

remove方法跟get方法很相似,只是在get的基础上增加了移除操作

	@Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }
    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;
            // 查找节点这个的步骤类似getNode里的操作
            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);
                // 当前节点正好是需要移除的节点,则是next节点指向索引位置.否则next指引前一个节点    
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

三.线程安全

HashMap与HashTable与concurrentHashMap的区别?
之前从关键源码可以看出,HashMap是线程不安全,并发存在隐患.为了解决这个问题,出现了HashTable和concurrentHashMap两个线程安全类.
HashTable这个类只是在每个方法添加Synchronize,虽然实现了线程安全,但是并发效率不好,目前基本不使用.
concurrentHashMap是一个线程安全且高效的HashMap实现,采用CAS + synchronized 来保证并发安全性.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值