HashMap源码阅读

HashMap内含字段说明

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
    // 默认的初始容量
	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
	
	static final int MAXIMUM_CAPACITY = 1 << 30;

	static final float DEFAULT_LOAD_FACTOR = 0.75f;
	// 桶中的链表的长度 大于 8就会执行树化操作,但是不一定会转成树,需要看MIN_TREEIFY_CAPACITY的值
	static final int TREEIFY_THRESHOLD = 8;
	//
	static final int UNTREEIFY_THRESHOLD = 6;
	//链表树化操作 桶的值, 例如	
	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;
}

put操作

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
	//put 方法 onlyIfAbsent=false 相同的key会替换值
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        // 临时变量声明 tab:桶;p:当前节点            
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 这个if就是看你桶有没有初始化,没有会进行初始化
        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);
        // 否则,就说明那个桶的位置被占了
        // 1:桶中第一个节点和我们添加的key相同,所以直接将添加值赋值到临时节点e中,
        //    后面再决定是否修改值  
        // 2: 当前桶取出的节点是树类型的,用树那种方法添加值
        // 3: 说明现在桶中的节点还没有树化,是以链表的方式存储的
        else {
        	// e:临时节点,引用类型,当原先HashMap中有相同key时,就进行赋值
            // 例如 e = p;两者都是指向同一个对象
            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 {
            	// 桶中的节点还是链表的方式
            	// 进行死循环,有两个break进行跳出死循环
            	// 1:链表已经完全遍历;2:遍历的过程中找到了相同的key  
                for (int binCount = 0; ; ++binCount) {
                	// p.next = null 说明遍历到链表尾部也没有找到一个相同的key
                	// 所以直接插入到链表的尾部
                	// (e = p.next) == null 源码很喜欢 比较过程中进行赋值操作
                	// 注意 e = p.next 这步进行了赋值,这步跟遍历途中找到相关key
                	// 然后决定是否覆盖值有关系
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        // 为什么 TREEIFY_THRESHOLD=8要减1,因为从零开始的呀
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        	//执行树化操作
                            treeifyBin(tab, hash);
                        break;
                    }
                    // 遍历的途中找到相同的key
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            // 有相同的key,通过onlyIfAbsent决定值进不进行值覆盖
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // hashMap的节点数 大于 扩容阈值就会触发扩容操作;扩容阈值计算也在扩容方法中进行计算
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }	

treeifyBin方法

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        // 小于 MIN_TREEIFY_CAPACITY = 64 就扩容 
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        // 计算节点在桶的位置,那个位置有节点    
        else if ((e = tab[index = (n - 1) & hash]) != null) {
        	// tl:含义上次的节点;hd:首节点
            TreeNode<K,V> hd = null, tl = null;
            do {
            	//由链表节点转成树节点
                TreeNode<K,V> p = replacementTreeNode(e, null);
                // 上次为空,说明是第一个
                if (tl == null)
                    hd = p;
                else {
                	//当前节点.前节点 = tl (上一次节点)
                    p.prev = tl;
                    tl.next = p;
                }
                // 本次遍历的节点复制给tl,所以tl的含义是上一个节点
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
            	//树化操作
                hd.treeify(tab);
        }
    }

resize方法

现在我们只注意初始化过程的

final Node<K,V>[] resize() {
		// 桶赋值给临时变量oldTab,
        Node<K,V>[] oldTab = table;
        // 桶的容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 要调整大小的下一个大小值(容量*负载系数)
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 第一部分判断桶是否有数据,计算容量和下次触发扩容值  if-else if-else
        //桶中数据
        if (oldCap > 0) { 
      
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                // 下次触发扩容值 等于现在扩容值乘以2     
                newThr = oldThr << 1; // double threshold
        }
        // oldThr = threshold; threshold:含义下次 扩容桶的大小,
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr; // HashMap(int initialCapacity) 这种方式会走这步,自己指定map的容量大小
        // else 桶没有初始化的情况,设置为默认的容量,下次扩容的大小 = 
        else {              
            newCap = DEFAULT_INITIAL_CAPACITY;
            // DEFAULT_LOAD_FACTOR =0.75f DEFAULT_INITIAL_CAPACITY=16
            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是处理桶扩容后,给原来的桶中节点搬到新 桶里面
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    // 桶中的节点 链表没有下一个元素,就是直接放到新桶中
                    // e.hash & (newCap-1) 计算新桶中的位置
                    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;
    }

tableSizeFor

我的推理

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

例如 536870934,

原数据 536870934
100000000000000000000000010110
n | n >>> 1 
110000000000000000000000011111
n | n >>> 2 
111100000000000000000000011111
n | n >>> 4 
111111110000000000000000011111
n | n >>> 8 
111111111111111100000000011111
n | n >>> 16 
111111111111111111111111111111
长度:30
n + 1 
1000000000000000000000000000000
长度:31
// 最后加1,就是像推多米诺一样

看上面 移动一位 或操作之后,得到两位1开头的
移动二位之后 或操作之后,得到四位1开头的

(((((1+1)+2)+4)+8)+16) = 32

就是翻倍的过程
最终 16*2 =32 位 就是int 长度

hash方法

^ 运算说明
参加运算的两个数据,按二进制位进行“异或”运算。

运算规则:0^0=0; 0^1=1; 1^0=1; 1^1=0;

   static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    // 等价于
    key.hashCode() ^ ( key.hashCode() >>> 16);
    // int h = key.hashCode() 说明是int,int 有32位,我把前16位称为高16,后面16位称为 低16
    // 那么就等价于16 + (16 ^16) 

猜测

(h = key.hashCode()) ^ (h >>> 16) 为什么用的是 ^ 而不是 & , | 
// & 运算 
0 & 0 = 0; 0 & 1 = 0; 1 & 0 = 0; 1 & 1 = 1;
所以 0 的概率是 3/4 , 1 的概率 是 1/4

// | 运算
 0 | 0 = 0; 0 | 1 = 1; 1 | 0 = 1; 1 | 1 = 1;
所以 1 的概率是 3/4 , 0 的概率 是 1/4

// ^ 运算
0 ^ 0 = 0; 0 ^ 1 = 1; 1 ^ 0 = 1; 1 ^ 1 = 0;
所以 1 的概率是 1/2 , 0 的概率 是 1/2
所以分布更加均匀

计算hash值在桶的位置

& 运算说明

参加运算的两个数据,按二进制位进行“与”运算。

运算规则:0&0=0; 0&1=0; 1&0=0; 1&1=1;

if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

不管hash值多大,最后的范围一定在 [0,n-1]中
因为n-1 ,前面值为0,所以 & 之后也为零

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值