HashMap注释版

1.HashMap的实现,讲的主要是jdk1.8的。HashMap中主要的知识点有:

1.使用的hash算法,也即hash(key)的计算逻辑

   /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
	 //之所以这样计算hash值的原因是,扩散key.hashCode()的高位到低位。由于
	 //table使用的是2的指数倍掩盖,许多在当前掩码上的hash总是产生冲突。
	 //(许多Float类型的key总是在小表上连续不断的冲突)。所以我们将高位上的影响下移。
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

2. put()方法的实现

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
 }

 /**
     * 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) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
		//如果table为null 或者长度为0,调用resize()方法,进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;

		//判断tab数组中的(n - 1) & hash的位置是否为null
        if ((p = tab[i = (n - 1) & hash]) == null)
			//如果为null,说明之前没有存放过数据,将新节点放入tab数组中
            tab[i] = newNode(hash, key, value, null);
        else {
			//说明tab[i]已经有数据了。可以考虑三种情况,
            Node<K,V> e; K k;
			//第一种是p.key==key,可以直接更新
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
			//第二种是p结点已经转换成红黑树的结构,可以把这个值存入的红黑树中。
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
				//第三种 是链表结构
                for (int binCount = 0; ; ++binCount) {
                    //判断下p.next是否为null,
					if ((e = p.next) == null) {
						//因为p.next == null,说明已经到了链表的尾部,可以直接插入结点
                        p.next = newNode(hash, key, value, null);
						//如果链表的长度大于等于8,调整成红黑树的结构
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
					//如果说e.hash == hash,同时e.key == k,说明是同一个结点,不用存储了,直接返回。
                    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;
				//onlyIfAbsent为true,则不改变e结点的值,但是在调用put方法的时候,
				//onlyIfAbsent为false,说明是要更新的value值的,
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
				//返回原来旧的value值
                return oldValue;
            }
        }
		//保留修改的次数,用于HashMap中迭代器的快速失败。
        ++modCount;
		//直接存放到数组中的个数大于阈值,就进行resize(),也就是扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

3. resize()方法的实现,就是扩容的实现

这里也存在一个疑问:oldTab[j] = 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;
        if (oldCap > 0) {
			//老的入量大于等于最大容量,直接返回老数组,不扩容了
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
			//oldCap的两倍为newCap ,如果newCap<MAXIMUM_CAPACITY,oldCap也大于默认的初始容量,就进行扩容
			//也说明newCap 为2 的指数倍增长
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
				//newThr 也是oldThr的2倍,也是指数倍增长
                newThr = oldThr << 1; // double threshold
        }
		// 
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
			//说明了oldCap 和oldThr都为0的情况,newCap为默认初始容量,newThr为默认初始容量*负载因子的取整
            newCap = DEFAULT_INITIAL_CAPACITY;
            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);
        }
		//---------------以上都为计算newCap和newThr 逻辑。
		//更新threshold属性的值为newThr
        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;
					//e是只有一个节点的链表,直接e.hash &(newCap-1),进行定位,e.hash & (newCap-1)其实也是等于e.hash&(oldCap-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;
						//遍历e节点的链表,把这个链表分成hi,lo两个链表,目的是可以缩短链表的长度,并能够是数据更加散列
                        do {
                            next = e.next;
                            //低位,lo到了newTab中还是原来的相对位置上,hi是j+oldCap的位置上
                            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);
						//lo链表存放到j的位置
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
						//hi链表存放到j+oldCap的位置
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

4. get()方法的实现

	  /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
     * key.equals(k))}, then this method returns {@code v}; otherwise
     * it returns {@code null}.  (There can be at most one such mapping.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     * The {@link #containsKey containsKey} operation may be used to
     * distinguish these two cases.
     *
     * @see #put(Object, Object)
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

	/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    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) {
			//直接定位到数组中对应的位置且key == key,直接返回第一个结点
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
			//说明first.key != key,需要在first.next节点中继续找
            if ((e = first.next) != null) {
				//如果是红黑树结点,直接在树中查找
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
				//在链表中查找,进行查找
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HashMap的元素数量超过了它的容量与负载因子的乘积时,就会调用resize方法进行扩容。扩容后,HashMap中的所有元素都需要重新计算其在新数组中的位置,并存储到新的数组中。 下面是resize方法的代码注释: ```java /** * 扩容HashMap,重新分配内存空间并重新计算每个元素的位置 * @param newCapacity 新的容量 */ final void resize(int newCapacity) { // 保存旧的数组 Node<K,V>[] oldTab = table; // 获取旧的容量 int oldCap = (oldTab == null) ? 0 : oldTab.length; // 如果旧的容量已经达到最大值,则无法继续扩容 if (oldCap == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } // 计算新的阈值 int newThr = (oldCap > 0) ? (int)(oldCap * loadFactor) : initialCapacity; // 如果新的阈值小于最小阈值,则将新的阈值设置为最小阈值 if (newThr < MINIMUM_CAPACITY) { newThr = MINIMUM_CAPACITY; } // 创建新的数组 @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCapacity]; // 更新阈值 threshold = newThr; // 将HashMap的table指向新的数组 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 & (newCapacity - 1)] = e; } // 如果当前节点有下一个节点,则需要遍历该链表,并将链表中的所有节点放置到新数组中对应的位置上 else if (e instanceof TreeNode) { ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); } else { // 该链表中的节点数小于等于TREEIFY_THRESHOLD(默认为8),则将该链表转换为普通链表 Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; // 如果节点的哈希值在旧数组中的位置为j,则将该节点放置在新数组中的位置上,否则放置在新数组中的位置(j+oldCap)上 if ((e.hash & oldCap)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值