Java集合之HashMap源码解析【面试题】

本文深入探讨了HashMap的工作原理,包括其数据结构、哈希值计算、PUT和GET方法的实现细节,以及扩容机制。通过理解Node类和红黑树转换,揭示了HashMap高效存储和检索键值对的秘密。

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

前言

在比较ArrayList和LinkedList的区别时,我们知道:

  • 数组,元素顺序存放,查找快,删除慢,插入慢。

  • 双向链表, 元素随机存放,查找慢,删除快,插入快

HashMap就是综合以上两种数据结构的优点,即数组+单向链表的方式实现,它是一种K-V键值对的存储结构

HashMap的数据结构

Node<K,V>是HashMap的基本元素单位,Node是一个静态内部类,源码如下:

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

在这里插入图片描述
Node这个静态内部类有四个成员属性,分别是:

  1. hash,即由key通过哈希函数计算得到的哈希值

  2. key,即键值对中的键

  3. value,即键值对中的值

  4. next,即Node节点的后继节点 ps(单向链表)

Hash值如何计算
static final int hash(Object key) {
         int h;
         return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
 }

如果key为null,hash为0 → HashMap的key允许为空,反之 (h = key.hashCode()) ^ (h >>> 16),即哈希值h与无符号右移16位后的值异或,这么做是为了减小运算量(相较于取模操作)

HashMap自身的成员变量如下:

transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
int threshold;
final float loadFactor;
  • table哈希表存放的是Node<>数组

  • entrySet是存放所有键值对的集合,可用于遍历

  • size是HashMap的元素个数,而capacity是指哈希表table的长度

  • modCount表示修改次数

  • loadFactor 装载因子用来衡量HashMap满的程度,默认值为0.75f,具体计算是size/capacity

  • threshold 扩容阈值,threshold = capacity * loadFactor,size超过阈值会进行resize扩容操作

PUT方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 如果table为空,或者还没有元素时,则扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    // 如果首结点值为空,则创建一个新的首结点。
    // 注意:(n - 1) & hash才是真正的hash值,也就是存储在table位置的index。在1.6中是封装成indexFor函数。
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {    // 到这儿了,就说明碰撞了,那么就要开始处理碰撞。
            Node<K,V> e; K k;
            // 如果在首结点与我们待插入的元素有相同的hash和key值,则先记录。
            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);
                            // 当遍历的结点数目大于8时,则采取树化结构。
                            if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                                treeifyBin(tab, hash);
                                break;
                        }
                        // 如果找到与我们待插入的元素具有相同的hash和key值的结点,则停止遍历。此时e已经记录了该结点
                        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
            // 表明,记录到具有相同元素的结点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);  // 这个是空函数,可以由用户根据需要覆盖
                return oldValue;
            }
        }
    ++modCount;
    // 当结点数+1大于threshold时,则进行扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict); // 这个是空函数,可以由用户根据需要覆盖
    return null;
}

在这里插入图片描述

GET方法

	public V get(Object key) {
            Node<K,V> e;
            //根据key的hash值和key寻找Node,如果为null则返回null,如果不为null则返回value
            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;
        //如果 tab部位null 并且 tab数组中有元素 并且 要查找的hash & (n-1) 在tab中存在
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
        	//判断如果hash和key都相同则返回该元素(返回的是tab数组中的节点元素,下面的判断才是链表里面的)
            if (first.hash == hash && ((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 {
                	//循环查找结点的下一个,直到找到hash和key同时相同的节点,返回改节点
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
                    	return e;
                    }
                    //用于循环判断下一个节点
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值