HashMap源码详细分析(上)

HashMap

数据结构

int size;				数据量
Node<K,V>[] table;		hash表
int threshold;			扩容临界点 threshold=table.length*loadFactor
float loadFactor;		填装因子

在这里插入图片描述
TreeNode、Node属性至关重要.

构造方法

public HashMap();			
				初始化factor
public HashMap(int initialCapacity)与
public HashMap(int initialCapacity, float loadFactor)
				初始化factor、threshoud=tablesizefor(initialCapacity);

查找大于等于cap,且最近的2的整数次幂的树,eg.10->16,5->8

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

在这里插入图片描述

resize方法

源码流程图:
在这里插入图片描述
在这里插入图片描述

			单链表copy						Node节点(单链表)
	遍历单链表分解成两个单链表,分别放置low位置,与high位置
			红黑树copy				TreeNode节点(利用了其双链表的性质)
	遍历单链表的分解成两个单链表A、B, 如果长度<=6解树
	解树:调用untreeify把树节点变成Node节点;	
	如果长度>6,调用treeify遍历链表重新构造红黑树;
	
	treeifyBin:把Node节点变成红黑树节点,并调用treeify
	treeify:把TreeNode节点构造成红黑树

源码分析

/hashMap扩容操作
// oldTab未扩容的桶,oldCap未扩容的桶大小,oldThr未扩容时的阈值;
// newTab扩容后的桶,newCap扩容后的桶大小,newThr扩容后的阈值;
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) 
	// 有参数的构造方法第一次put会进到这里;
//初始化table为空,initSize经过tableSizeFor运算返回一个数,这个数是2^n并且大于等于initSize;取最小2^n值;把这个数作为table第一次初始化的大小
        newCap = oldThr;//把计算好的阈值设置为下次要扩容的大小
    else {               // 无参构造方法第一次进入这里
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {
	//有参数的构造方法第一次put会进到这里;
//在这里重新计算扩容后的阈值
        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];//新建一个nodeTable
    table = newTab;//把原来的table指向新table
    if (oldTab != null) {
//如果是扩容操作就把原来的数据放到新的table中
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;
                if (e.next == null)//原来位置上只有一个node的直接挪过去
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)
		//原来位置是红黑树的拆分红黑树
                    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                else { //原来是链表的拆分链表
		//拆分之后的位置,要么在原来的位置不变,要么在原来的位置上的基础上+扩容的大小的位置上;
		// loHead:原来位置上的链表头, loTail:原来位置上链表尾
                    Node<K,V> loHead = null, loTail = null;//原来的位置
	// loHead:新位置上的链表头, loTail:新位置上链表尾
                    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、balanceInsertion方法

源码流程图:
在这里插入图片描述

//hashMap插入操作
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
// onlyIfAbsent=true,则不允许覆盖; evict=false,在构造模式下(HashMap第四个构造函数)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
// tab:桶;p:当前节点; n:桶的大小; i:p在桶的位置 
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;//桶为空或者长度为0扩容
    if ((p = tab[i = (n - 1) & hash]) == null)
//如果在桶中的位置为空,把桶的值设置为Node
        tab[i] = new Node(hash, key, value, null);
    else {//1.桶中已经有node ; 2.链表  3.红黑树
        Node<K,V> e; K k;
//e最终指向oldValue(最后用Value覆盖oldValue)
//k:e
        if (p.hash == hash &&  
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
//1.桶中的node的key和传入的key相同,进行覆盖操作
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//3.红黑树插入操作


        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;
            }
//2.链表插入操作
        }
//e指向oldValue,把Value对oldValue覆盖
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
//覆盖就返回oldValue
            return oldValue;
        }
    }
//非覆盖返回null,容器修改的次数+1
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
//计算key值在桶中的位置
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

putTreeVal

//在红黑树中找到合适的位置并插入
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;
        if ((ph = p.hash) > h)//左子树
            dir = -1;
        else if (ph < h)//右子树
            dir = 1;
        else if ((pk = p.key) == k || (k != null && k.equals(pk)))
            return p;//key相同返回节点
	//key的hash相同,但是却是不同的东西,使用另外的手段确定位置
        else if ((kc == null &&
                  (kc = comparableClassFor(k)) == null) ||
                 (dir = compareComparables(kc, k, pk)) == 0) {
            if (!searched) {
                TreeNode<K,V> q, ch;
                searched = true;
                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;
            }
            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;
            if (xpn != null)
                ((TreeNode<K,V>)xpn).prev = x;
	    //插入之后,把树的root节点按照它的链式结构移动到链头
	    //这里的TreeNode,不仅是一种树结构,还保存了双链表结构,把树的root节点和链表头节点设置成同一个节点,其树结构用于快速查找,链表结构遍历整棵树或者使用链表遍历拆分整棵树,
            moveRootToFront(tab, balanceInsertion(root, x));
            return null;
        }
    }
}

tieBreakOrder:当key的hash值相同,且key都没有实现comparable时,定义一个新的比较方法

treeifyBin

作用:Node节点转换成TreeNode节点,并调用treeify

//Node节点转换成TreeNode节点
final void treeifyBin(Node<K,V>[] tab, int hash) {
    int n, index; Node<K,V> e;
    if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
        resize();//当桶的容量<64时,优先考虑扩容
    else if ((e = tab[index = (n - 1) & hash]) != null) {
//依次把桶上指定位置的链表节点转换为树节点
//hd指向头节点,t1执行e的前一个节点
        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);
    }
}

treeify

作用:遍历TreeNode节点,构造红黑树

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;
                if ((ph = p.hash) > h)//左
                    dir = -1;
                else if (ph < h)//右
                    dir = 1;
//hash相同,但类却不同,使用其他方法比较
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0)
                    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;
                }
            }
        }
    }
//root节点移动到链头
    moveRootToFront(tab, root);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HashMap是Java中的一个常用的集合类,用于存储键值对的数据结构。它的底层数据结构是数组、链表和红黑树。HashMap可以存储null的键和值。下面是对HashMap源码详细分析。 1. HashMap的特点:HashMap是无序的,不保证元素的顺序。它允许使用null作为键和值。HashMap不是线程安全的,如果在多线程环境下使用,需要进行额外的同步。 2. HashMap的构造方法: - HashMap():创建一个空的HashMap实例,默认初始容量为16,负载因子为0.75。 - HashMap(int initialCapacity):创建一个指定初始容量的HashMap实例。 - HashMap(int initialCapacity, float loadFactor):创建一个指定初始容量和负载因子的HashMap实例。 - HashMap(Map<? extends K, ? extends V> m):创建一个包含指定Map中所有键值对的HashMap实例。 3. HashMap的成员方法: - put(K key, V value):向HashMap中添加键值对。 - hash方法:计算键的哈希值。 - 扩容方法resize():当HashMap的大小达到阈值时,会自动扩容。 - 删除方法remove():根据键删除对应的键值对。 - 查找元素方法get():根据键获取对应的值。 4. HashMap的常见问题: - HashMap的容量为什么是2的幂次方?这是为了提高哈希函数的散列性能和数组的索引计算效率。 - 为什么负载因子默认是0.75?这是为了在保持较高的查找效率的同时,尽可能减少哈希冲突和扩容次数。 综上所述,HashMap是一种底层使用数组、链表和红黑树的存储方式的键值对集合类,并提供了一系列的方法来操作和查询数据。它的源码实现细节涉及到数组的扩容、哈希函数的计算、链表和红黑树的操作等。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [最详细的Hashmap源码解析](https://blog.csdn.net/qq_45830276/article/details/126768408)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [HashMap源码解析](https://blog.csdn.net/weixin_46129192/article/details/123287837)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值