HashMap源码解析

重要属性分析

	/**
     * 默认初始容量, 当我们new空参构造器,第一次add时会扩容为16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

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

    /**
     * 链表数量超过8时,会考虑变成树形结构(红黑树)
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 小于6时恢复链式结构
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * 只有hash桶的数量>=64时,才会真正将链式结构变成红黑树
     * 否则,仅仅采用扩容的方式尝试减少冲突
     */
    static final int MIN_TREEIFY_CAPACITY = 64;
    /**
     * hash表,可以看到是Node数组
     */
    transient Node<K,V>[] table;

    /**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
    transient Set<Map.Entry<K,V>> entrySet;

    /**
     * 记录此时键值对的个数(注意,这里并不像ArrayList中有一个length和一个size)
     */
    transient int size;

    /**
     * HashMap 进行结构性调整的次数。结构性调整指的是增加或者删除键值对等操作,
     * 注意对于更新某个键的值不是结构特性调整。
     */
    transient int modCount;

    /**
     * The next size value at which to resize (capacity * load factor).
     * 计算的扩容临界值
     */
    int threshold;

    /**
     * The load factor for the hash table.
     */
    final float loadFactor;

内部类Node说明

	/**
     * Note:
     * Node中时刻记录了该对象的hash值
     * next指针可以指向后续节点
     */
	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;
        }
    }

构造方法分析

	/**
     * 传入指定的初始容量和负载因子
     * 1.给this.loadFactor赋值
     * 2.注意会对传入的initialCapacity进行调整,返回一个2的幂次方的数(tableSizeFor函数)
     * 3.同时给this.threshold赋值
     * 
     * 4.一定要注意:此时table并未初始化!
     */
    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);
    }

    /**
     * 给定一个默认加载因子
     * 注意:我们这里可以传入0,但是此时table依旧没有被初始化,而且此时threshold也是0
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    /**
     * 1.此时没有修改this.threshold(依旧是初始值0)
     * 2.默认加载因子
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

特殊方法分析

	/**
     * Returns a power of two size for the given target capacity.
     * 返回cap的2的幂次方(注意函数最后返回的是n + 1)
     * 
     * 原理:让数n的二进制位最高位为1的后面的二进制位全部变成1
     * 
     * 这样做的原因:
     * 扩容:扩容的时候,哈希桶扩大为当前的两倍,因此只需要进行左移操作即可
     * 取模:由于哈希桶的个数为2的幂次,因此可以用&操作来替代耗时的模运算,
     *  n % table.length -> n & (table.length - 1) 
     * 
     * 如果不这样做,会有hash桶一直用不到。如果size=5,那么0100只能用到第0或者4个桶!
     */
    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;
    }
    /**
     * hash的计算方法:自身的hashCode与高16位的hash值做了一个异或运算(向右移动16位)
     * 原因:假设此时哈希表的长度为64,那么定位n属于哪个桶的方法:
     * n & 0111111, 可以发现我们只能使用到n的后6位!
     * 
     * 总结:如果hash的高位变化很大,低位变化很小,这样就很容易造成冲突;所以,这里把高位
     * 和低位都利用起来,一定程度上解决冲突问题。
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

get方法深挖

	/**
     * 调用getNode方法(传入了hash值和key),判断返回值是不是null
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 1.通过(n-1) & hash(传入的key的hash值),计算桶的位置
     * 2.如果桶上的Node对象(first)就是我们要查找的,则直接返回
     * 3.否则遍历链表
     * 		3.1 判断如果是数节点,通过调用树的方式进行查找
     * 		   (TreeNode继承了LinkedHashMap.Entry,后者实现了HashMap.Node)
     * 		3.2 否则,遍历链表查找。
     * 
     * 参数说明:
     * tab就是我们的哈希表table, n存储哈希表的length; first存储定位的哈希桶的Node对象
     * k 存储临时的key值;e就是一个临时指针,用来遍历链表
     */
    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;
    }

put方法深挖

	/**
     * 1.计算key的hash
     * 2.调用putVal方法
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Note:如果插入成功返回null,如果失败返回oldValue(更新value)
     * 
     * 1.如果table是null(不管哪种构造器,都没有初始化table);或者table.length=0;
     *   需要首先使用resize方法初始化一个哈希表,同时将长度给n
     * 2.如果此时hash桶上没有元素,通过newNode方法new一个Node对象放在tab[i]上即可
     * 3.出现冲突,需要处理冲突:
     * 	3.1 如果此时桶上的节点和当前key重复,则就是我们要找的节点;此时会更新val,并返回oldValue
     * 	3.2 如果采用红黑树处理冲突,调用putTreeVal方法插入这个键值对
     * 	3.3 否则,就是传统的链式结构;会遍历链表
     * 		3.3.1 如果碰到null,说明没有重复key(都是通过hash值+equals方法判断);
     * 			  此时直接插入到链表最后;注意需要判断:binCount >= TREEIFY_THRESHOLD - 1
     * 
     * 		3.3.2 如果碰到重复key,跳出循环;更新value,返回oldValue。
     * 
     * 4. 如果插入成功(不包括更新oldValue),继续下面步骤
     * 	4.2 修改modCount
     * 	4.1 更新size,判断是否需要扩容,需要的话会调用resize方法
     */
    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)
        	// 注意:我们实际put数据时,都是在底层重新new对象;所以,如果我们直接put引用类型的话,那么就算再将该引用类型置空也无所谓
            tab[i] = newNode(hash, key, value, null);
        else {
       	    // 3. 出现冲突,需要处理
            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 {
                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;
    }

补充树化方法:

	/**
     * 我们可以很清楚的看到:
     * 如果n = tab.length) < MIN_TREEIFY_CAPACITY,仅仅是扩容!
     */
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        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);
        }
    }

remove方法分析

	/**
     * 调用removeNode实现功能:返回null或者value
     */
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * 1.定位的hash桶如果是null,则直接返回null
     * 2.如果桶上的节点就是我们要找的key,则直接命中(判断方法:hash值相同&&(key地址值相同||equals方法返回true))
     * 3.1 使用红黑树的方式处理冲突
     * 3.2 遍历链表处理冲突
     * 
     * 4. 如果能找到进行一下处理,否则直接返回null
     * 4.1 如果是TreeNode,则采用removeTreeNode方法
     * 4.2 通过链表的方法删除
     * 4.3 修改modeCount和size
     */
    final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

最重要的方法:resize

	/**
     * 1. 计算扩容后的容量和阈值:newCap和newThr
     * 		1.1 如果oldCap>0,则newCap和newThr都是通过位运算扩大2倍
     * 		1.2 oldThr>0(new构造器时自定义容量了), newCap=oldThr(调整后的自定义容量值)
     * 		1.3 newCap默认是16,newThr是通过0.75*16计算而来
     * 
     * 2. 创建newCap大小的数组:Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];并赋值给this.table
     * 
     * 3.1 如果oldTab==null,说明是第一次扩容,直接返回即可
     * 3.2 遍历oldTab中每一个桶,并重新计算在newTab中的新位置:
     * 		3.2.1 如果桶上只有一个Node,直接插入即可
     * 		3.2.2 如果桶上是TreeNode,通过一个split方法把树分离开
     * 		3.2.3 链表方式处理冲突,重新计算新的存储位置
     * 
     * 4.补充:如何计算oldTab中hash桶在newTab中的新位置?(源码中一共有两种方法)
     * 	4.1 源码:e.hash & oldCap) == 0 则位置不变
     *  4.2 否则,就是 原位置+oldCap (下图详细介绍)
     * @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<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)
                    	// 1. 计算hash桶的新位置
                        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;
                            // 2. 计算hash桶的新位置
                            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;
    }

计算hash桶新位置的方法:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值