0
点赞
收藏
分享

微信扫一扫

【java】hashMap的底层原理

weipeng2k 2022-04-05 阅读 25
java

问题描述


  • 初识HashMap从HashSet的扩容机制谈起
  • 源码:
    	Set set = new HashSet<>();
    	set.add("张大帅");
    	set.add("张少帅");
    	set.add("张大帅");
    	
    	// 1、调用无参构造器 返回在HashSet中初始化HashMap对象
    	public HashSet(){
        	map = new HashMap();
        }
    	
    	// 2、调用HashSet的add方法
    	public boolean add(E e) {
    		// PRESENT是hashSet的静态对象 用于占位 
    	    // Dummy value to associate with an Object in the backing Map
            return map.put(e, PRESENT)==null;  
        }
        
         // 3、调用hashMap的put方法 hash值作为table的索引
         public V put(K key, V value) { // key=“张大帅” value = static final new Object();
              return putVal(hash(key), key, value, false, true);
         }
    	 
    	 // 4、计算hash值,使用key的hashCode值及hashCode值无符号右移16做异或运算的结果,目的是减少hash冲突
    	 static final int hash(Object key) {
         	int h;
         	// key不为空,key的hashCode
         	// ^ 表示异或运算:相同置0,不同置1
         	// >>> 16 右移16位 高16位可以减少hash冲突
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); 
         }
         // 5、HashMap 的 putVal() 方法
         /**
        * Implements Map.put and related methods
         *
         * @param hash hash for key
         * @param key the key
         * @param value the value to put
         * @param onlyIfAbsent if true, don't change existing value
         * @param evict if false, the table is in creation mode.
         * @return previous value, or null if none
         */
        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                       boolean evict) {
            // 1、辅助变量初始化
            Node<K,V>[] tab; Node<K,V> p; int n, i;
            // 2、table 是 HashMap的一个属性 类型为 Node[]
            //   判断当前table为空 或者 tab.length == 0, 执行resize()table扩容方法
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            // 3、根据key得到hash索引值,找到key在table对应的位置索引位置 
                 // 并且 把这个位置的对象赋给p 
            // 4、p是否为null
            if ((p = tab[i = (n - 1) & hash]) == null)
            	// 如果p为空 表示当前位置没有存放元素,
            	// 新建一个该key的Node对象 Node(key="张大帅"value=PRESENT)
                tab[i] = newNode(hash, key, value, null);
            else {
            	// p不为空,代表当前table索引位置存在 单链表
                Node<K,V> e; K k;
                // 判断 当前数组位置的第一个Node节点key与传入key作比较
                // 满足:(1)两者hash值相等
                //      (2)两者引用地址或值相等
                // 则认为 传入的key存在 
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                // 判断 当前节点是TreeNode的实例,将table转为红黑树
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {
                	// 当前链表已存在,for循环指向下一节点
                    for (int binCount = 0; ; ++binCount) {
                    	// 下节点为空,没有发现相同的key,就自动加到链表末尾,跳出
                        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;
                        }
                        // 判断key是否相同,相同跳出
                        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;
                }
            }
            // 操作数+1
            ++modCount;
            // node数是否超过临界长度
            if (++size > threshold)
            	// 超过扩容
                resize();
            // 留给子类实现链表排序的方法,默认
            afterNodeInsertion(evict);
            return null;
        }
    
        /**
         * Initializes or doubles table size.  If null, allocates in
         * accord with initial capacity target held in field threshold.
         * Otherwise, because we are using power-of-two expansion, the
         * elements from each bin must either stay at same index, or move
         * with a power of two offset in the new table.
         *
         * @return the table
         */
        final Node<K,V>[] resize() {
            Node<K,V>[] oldTab = table;
            // 旧容量值
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            // 旧的临界值
            int oldThr = threshold;
            // 初始化新的容量和临界值
            int newCap, newThr = 0;
            // 旧的容量值大于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
            }
            // 旧的临界值大于0
            else if (oldThr > 0) // initial capacity was placed in threshold
                newCap = oldThr;
            // 两者均为0
            else {               // zero initial threshold signifies using defaults
                newCap = DEFAULT_INITIAL_CAPACITY; // 新的容量 默认 16
                // 新的临界值 = 加载因子(0.75)* 默认容量值
                // 如果当前table数组使用已达到临界值,就扩容
                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数组,作为链表
            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 { // 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;
        }
    
        /**
         * Replaces all linked nodes in bin at index for given hash unless
         * table is too small, in which case resizes instead.
         */
        final void treeifyBin(Node<K,V>[] tab, int hash) {
            int n, index; Node<K,V> e;
            // 表为空或者 表的实际长度 小于 链表转红黑树的最小容量(1 >> 4)64 
            // 只对表的长度进行扩展
            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 {
                    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);
            }
    	}
    
举报

相关推荐

0 条评论