从源码分析HashMap的实现原理

HashMap整体分析

 HashTable继承Map接口,提供了map中所有的操作并且等价于HashMap,除了它是多线程的并且允许为多个null值。
 
 基础的操作为get、put操作,通过hash函数将元素放到桶中,遍历集合需要时间去计算HashMap的容量(桶的数量以及key-value中值的数量)最重要的是设定初始化的容量

 HashMap有两个重要参数:初始化容量、加载因子。
 在HashTable中容量就是桶的数量
 当这个当前数量在HashTable中超出了在加载因子和当前容量的值,Hashtable会重新进行hash(数据重新排列)
 因此HashTable大约有两次计算桶的操作。

 默认的加载因子是0.75,这个值是保证空间和时间的消耗都是稳定的。加载因子过高会降低空间的管理时间,但是增加了查找的时间(影响到的操作有HashMap中的get、put操作)
 这是在Map中最期望的大小并且当初始化容量时就应该设定加载因子,目的时减少重新hash的数量。如果初始化容量比被加载因子分隔开的最大的值要更合适,那么重新hash操作将不会出现。
 
 
 需要注意的是HashMap不是同步的也就是不支持多线程,也就是只有一个线程在当前map中执行。
 如果大量的线程执行在一个HashMap中,通常通过多线程对象来封装这个map完成多线程问题。
 
 如果不存在这样的对象,那么可以使用Collections中的synchronizedMap方法,
 方法如下:Map m = Collections.synchronizedMap(new HashMap(...));


1、默认值的分析

    
	 //初始化容量
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    
	 //最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    
	 //默认加载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    
	 //链表转红黑树的阈值值,意思为当存储的值必须大于2并且至少为8,这是为了减少树向链表转换时的收缩率。
    static final int TREEIFY_THRESHOLD = 8;

    
	 //树转换为链表的阈值
    static final int UNTREEIFY_THRESHOLD = 6;

    
	 //初始化容量的大小,这个值最小为4*6(红黑树转换链表的阈值)这是为了避免重新调整大小以及设定阈值的复杂化。
    static final int MIN_TREEIFY_CAPACITY = 64;

    
	 //Node节点类,继承Map.Entry类,并且定义了equals方法,用来比较两个值是否相等。
    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;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

	 //hash函数,用来计算key值的hash值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    

    /**
     * Returns k.compareTo(x) if x matches kc (k's screened comparable
     * class), else 0.
     */
    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

   
	 //计算大小的方法,每次都是2的倍数,如果设定大小为10,那么会寻找大于10的2的倍数,也就是16,一次类推
	 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;
    }

    /* ---------------- Fields -------------- */

    
	 //初始化map时调用
    transient Node<K,V>[] table;

    
    
	 //在map中key-value数量的大小
    transient int size;

  

   
	//阈值,大于当前阈值,需要增加容量,通过最大容量和加载因子的乘积计算出
    int threshold;

    
	 //加载因子的表
    final float loadFactor;

    
	 //有参构造函数,初始化threshold的值,通过初始化容量以及加载因子设定
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

    
	 
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    //无参构造函数
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    
	 //参数为一个Map,设定加载因子,然后执行putMapEntries方法来遍历参数Map的值,放到新的Map中
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

2、get方法分析

	//get方法,通过key获取value,调用hash方法来计算key的hashcode,将hashcode作为参数调用getNode方法
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
	 //通过key来判断是否包含该值,依然需要调用hash函数来计算hashcode进行判断
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    
	 //先判断第一个是否为要查询的值,如果是则返回,否则继续遍历下一个节点,判断节点是否在TreeNode节点中
	 //如果在TreeNode节点中,则该节点是红黑树的结构,则需要调用getTreeNode方法来查询value
	 //否则就继续查询然后返回对应的值
    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)
                    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;
    }

3、put方法分析

 //put方法,在put方法中调用了putVal方法,putVal方法最终执行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类型,不可继承不可重写,四个参数分别为:key的hashcode、key、value、是否更改现有的值、判断上一个值如果没有则为null
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
		//判断是否为map是否为null,如果为null则计算大小。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
			//判断链表中是否有该值,若没有则重新创建一个Node节点。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
		//如果有该值,则判断hash值是否相同,若相同再通过equals判断值是否相等
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
				//判断是否为树节点,如果为树节点则调用putTreeVal方法进行put值
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
				//此处是判断链表转红黑树的操作,该操作中通过在循环中判断链表中的大小是否大于了8,如果大于等于7则执行treeifyBin方法进行链表转红黑树操作。
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, 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))))
                        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;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

4、扩容分析

 /**
     * 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;
            }
            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);
        }
        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;
		//将原来的Node数组的值放到新的Node数组中
        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)
					//每次扩容都是2的倍数,因此将值放在新数组中,通过hash值与新数组的长度进行 与 操作计算位置,因此影响位置的数据只有最高位的一位。
					//比如扩容前的大小为8,数据A的hash值为0111,则定位为0011&(8-1)=0111&7=0111&111 = 0011
					//扩容后的大小为16,数据A重新计算位置,则0011&(16-1)=0111&1111=0011,两次的位置相同
					//因此通过e.hash&oldCap,0011&8=0011&1000=0,表示数据A的位置没有发生变化。
                        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;
							//该操作不需要重新计算hash,此处通过hash与原来的长度进行 与 操作,根据结构是否为0来做对应的处理
							//如果是0则位置没有发生变化,如果不为0则发生变化
                            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;
    }

5、链表转红黑树分析

	 //链表转红黑树的方法
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
		//判断数组的大小是否小于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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值