Java 从源码简单的看hashMap实现原理

本文深入解析了HashMap的内部实现,包括默认初始容量、负载因子、树化阈值等关键参数,以及get、put操作的实现逻辑。在扩容机制上,详细阐述了如何通过resize()方法来应对容量不足的情况。通过对Node结构和哈希函数的理解,揭示了HashMap高效查找和存储的秘密。

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

部分常量解释

/*hashmap默认初始容量为16	The default initial capacity - MUST be a power of two.*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
/*已用达到0.75后会进行扩容	The load factor used when none specified in constructor.*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/*将链表转化成树的最小Node数量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;
/*将链表转化成树的最小总Node数量
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;//treeifyBin调用,若容量小于此值,直接resize();

Node结构

   static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;
        /*......*/
   }
   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
   }

get的实现–调用getNode

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;
            if ((e = first.next) != null) {  											
                if (first instanceof TreeNode)									//first对应树
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {															//first对应链表,顺序查找
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;															//未找到key
    }

put方法的实现–调用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;
        if ((tab = table) == null || (n = tab.length) == 0)
            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 &&												//碰撞处第一个Node的key符合	
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)										//碰撞Node对应的是树
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {														//碰撞Node对应的是链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {									//整条链表都没发现key,就在末尾new
                        p.next = newNode(hash, key, value, null);					//此时e为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))))		//找到key,e即对应的Node
                        break;
                    p = e;
                }
            }
            if (e != null) { 							// existing mapping for key,size没变,不需要resize()
                V oldValue = e.value;					
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;						//覆盖value
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();									//如果需要扩容的话就扩容,详见resize
        afterNodeInsertion(evict);
        return null;
}

扩容机制–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) // 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);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值