HashMap源码解析(JDK1.8)

作者: 奔跑吧李博 | 来源:发表于2020-09-10 09:36 被阅读0次

    HashMap的实现用的是数组+链表+红黑树的结构,也叫哈希桶,在jdk 1.8之前都是数组+链表的结构,因为在链表的查询操作都是O(N)的时间复杂度,如果当节点数量多,转换为红黑树结构,那么将会提高很大的效率,因为红黑树结构中,增删改查都是O(log n)。

    HashMap属性代码:
    public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {
        //序列号,序列化的时候使用
        private static final long serialVersionUID = 362498820763181265L;
        //默认容量,为2的4次方,即为16
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
        //最大容量,为2的30次方。
        static final int MAXIMUM_CAPACITY = 1 << 30;
        //加载因子,用于扩容使用。
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
        //链表转成红黑树的阈值。即在哈希表扩容时,当链表的长度(桶中元素个数)超过这个值的时候,进行链表到红黑树的转变
        static final int TREEIFY_THRESHOLD = 8;
        //红黑树转为链表的阈值。即在哈希表扩容时,如果发现链表长度(桶中元素个数)小于 6,则会由红黑树重新退化为链表
        static final int UNTREEIFY_THRESHOLD = 6;
        //当整个hashMap中元素数量大于64时,也会进行转为红黑树结构。
        static final int MIN_TREEIFY_CAPACITY = 64;
        //哈希桶数组,分配的时候,table的长度总是2的幂,transient关键字表示该属性不能被序列化
        transient Node<K,V>[] table;
        //将数据转换成set的另一种存储形式,这个变量主要用于迭代功能。
        transient Set<Map.Entry<K,V>> entrySet;
        //元素数量
        transient int size;
        //统计该map修改的次数
        transient int modCount;
        //临界值,也就是元素数量达到临界值时,会进行扩容。
        int threshold;
        //加载因子
        final float loadFactor;
    }
    

    HashMap提供3个构造方法:

        public HashMap() {
            this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
        }
    
        public HashMap(int initialCapacity) {
            this(initialCapacity, DEFAULT_LOAD_FACTOR);
        }
    
        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);
        }
    
    

    第一个初始化默认加载因子,第二个设置初始容量,初始化默认加载因子,第三个设置初始容量和默认加载因子。

    HashMap内部类TreeNode,该类是一个红黑树结构。

        static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> {
            TreeNode<K,V> parent;  // red-black tree links
            TreeNode<K,V> left;
            TreeNode<K,V> right;
            TreeNode<K,V> prev;    // needed to unlink next upon deletion
            boolean red;
            TreeNode(int hash, K key, V val, Node<K,V> next) {
                super(hash, key, val, next);
            }
    }
    

    HashMap内部类Node, 结构为单向链表:

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

    HashMap添加元素:

        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    
        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;
    
            //如果计算出的该哈希桶的位置没有值,则把新插入的key-value放到此处
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
                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;
                    }
                }
    
                //已存在该key,则用待插入值进行覆盖,返回旧值
                if (e != null) { // existing mapping for key
                    V oldValue = e.value;
                    if (!onlyIfAbsent || oldValue == null)
                        e.value = value;
                    afterNodeAccess(e);
                    return oldValue;
                }
            }
            //添加元素修改次数也会+1
            ++modCount;
            //实际长度+1,判断是否大于临界值,大于则扩容
            if (++size > threshold)
                resize();
            afterNodeInsertion(evict);
            return null;
        }
    
    上面用到方法hash,用于计算对象hash值
        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    

    先获取到key的hashCode,然后进行移位再进行异或运算,复杂的计算目的是为了尽可能减少hash冲突。

    HashMap获取元素:

        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) {
                //如果是头结点,则直接返回头结点
                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;
        }
    

    参考文章:
    HashMap源码解析JDK1.8

    HashMap 源码分析

    相关文章

      网友评论

        本文标题:HashMap源码解析(JDK1.8)

        本文链接:https://www.haomeiwen.com/subject/spysektx.html