• Java容器解析:HashMap(方法源码分析)


    前言

    HashMap是一个散列表,它存储的内容是键值对(key-value)映射。

    1 定义

    public class HashMap<K,V> extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable {
    
    }
    

    由HashMap定义可以看出

    1) HashMap<K,V>表示支持泛型
    2)继承自AbstractMap抽象类,实现对于Map容器的操作方法。
    3)实现Map接口,实现Map接口中定义的诸多方法。
    4)实现Cloneable接口,
    5)实现Serializable接口,保证容器的可序列化。
    

    2 属性值

    HashMap的属性值含义已在代码注释中给出。

     //默认初始化容量大小,必须为2的幂的数,初始为16
        static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 
        //最大容量值
        static final int MAXIMUM_CAPACITY = 1 << 30;
        //默认负载因子为0.75,代表table的填充度
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
        //链表长度阈值,HashMap采用数组+链表形式存储
        //当链表长度过长影响查询效率,因此当链表长度超过此值时,链表转为红黑树形式存储,以提升效率。
        static final int TREEIFY_THRESHOLD = 8;
    
        static final int UNTREEIFY_THRESHOLD = 6;
        //树最小容量
        static final int MIN_TREEIFY_CAPACITY = 64;
        //存储节点的数组
        transient Node<K,V>[] table;
        
        transient Set<Map.Entry<K,V>> entrySet;
        // 容器中键值对的数目
        transient int size;
        
        transient int modCount;
        //阈值,超过阈值则需要扩容
        int threshold;
        //负载因子
        final float loadFactor;
        
        //节点数据结构
        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;
            }
        }
    

    3 构造方法

    1) 无参数

    //采用默认值初始化
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    

    2)初始化容量为initialCapacity

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

    3)初始化容量为initialCapacity,负载因子为loadFactor

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

    4)使用集合初始化

      public HashMap(Map<? extends K, ? extends V> m) {
            this.loadFactor = DEFAULT_LOAD_FACTOR;
            putMapEntries(m, false);
        }
        //遍历集合,将集合中元素添加到this容器中
        final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
            int s = m.size();
            if (s > 0) {
                if (table == null) { // pre-size
                    float ft = ((float)s / loadFactor) + 1.0F;
                    int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                             (int)ft : MAXIMUM_CAPACITY);
                    if (t > threshold)
                        threshold = tableSizeFor(t);
                }
                else if (s > threshold)
                    resize();
                for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                    K key = e.getKey();
                    V value = e.getValue();
                    putVal(hash(key), key, value, false, evict);
                }
            }
        }
    

    4 核心方法

    方法 含义 时间复杂度
    get(Object key) 根据key获取value O(1)
    put(K key, V value) 存储键值对 O(1)
    containsKey(Object key) 是否包含key O(n)
    containsValue(Object value) 是否包含value O(n)
    remove(Object key) 删除key对应的value O(n)
    size() 容器元素数目 O(1)
    isEmpty() 集合是否为空 O(1)
    clear() 清空集合 O(n)

    5 put()方法

    put()方法添加键值对。在分析put()过程中会发现HashMap中有红黑树的实现过程。HashMap是采用数组加链表的方式存储数据的,当链表长度过长时影响查找效率,因此当链表长度超过一定阈值时,将链表结构转为红黑树存储,提升查找效率。

        //添加键为key,值为value
        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;
            //如果当前数组为空,或者表长度为0,调用resize()方法重新分配容量
            if ((tab = table) == null || (n = tab.length) == 0)
                n = (tab = resize()).length;
            // 如果数组中对应的索引位置的节点p为空,即不存在冲突情况,直接将键值对存储在索引为i位置。
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            
            //若存在冲突,则需要遍历链表寻找添加位置
            else {
                Node<K,V> e; K k;
                //如果节点p的键值与待存储节点的键值相同,将p节点赋给e节点
                //后面会对e几点进行判断,如果不为空,则将e节点的值赋值为value,采用替换的方式存储新的键值对,保证key的不可重复。
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    e = p;
                // 如果p节点的类型是TreeNode,,说明此时p节点所处的链表已经转为红黑树存储的方式。则调用红黑树的添加节点方法,添加新的节点 
                else if (p instanceof TreeNode)
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                //p节点的键不重复,且当前仍采用链表形式存储 ,则遍历p节点为头节点的链表
                else {
                    //链表的遍历,binCount记录链表的长度
                    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的作用在于将链表结构改为红黑树存储
                               treeifyBin(tab, hash);
                            break;
                        }
                        
                        // 在遍历链表过程中发现了有相同key的节点,则采用替换方式。
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            break;
                        p = e;
                    }
                }
                //如果e节点不为空,说明存在相同key,则替换此节点的value,并返回旧的value
                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;
        }
    
        //resize方法进行重新分配容量
        final Node<K,V>[] resize() {
            //获取旧表
            Node<K,V>[] oldTab = table;
            //旧表为空oldCap=0,否则oldCap = 旧表长度
            int oldCap = (oldTab == null) ? 0 : oldTab.length;
            // 存储旧阈值
            int oldThr = threshold;
            int newCap, newThr = 0;
            //旧表不为空
            if (oldCap > 0) {
                // 原数组长度大于最大容量(1073741824) 则将threshold设为Integer.MAX_VALUE=2147483647
                    // 接近MAXIMUM_CAPACITY的两倍
                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
                // 如果原来的thredshold大于0则将容量设为原来的thredshold
                // 在第一次带参数初始化时候会有这种情况
                newCap = oldThr;
            else {               // zero initial threshold signifies using defaults
                // 在默认无参数初始化会有这种情况
                newCap = DEFAULT_INITIAL_CAPACITY;
                newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
            }
            
            if (newThr == 0) {
                // loadFactor 哈希负载因子 默认0.75,可在初始化时传入,16*0.75=12 可以放12个键值对
                float ft = (float)newCap * loadFactor;
                newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                          (int)ft : Integer.MAX_VALUE);
            }
            //设置新的临界值
            threshold = newThr;
            @SuppressWarnings({"rawtypes","unchecked"})
            //扩容操作,创建新的容量大小的数组newTab
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            // 如果原来的table有数据,则将数据复制到新的table中
            if (oldTab != null) {
                // for循环遍历旧数组
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        if (e.next == null)//如果当前节点不存在下一个节点,即此节点为存储在数组中的节点
                            //将节点e添加至数组索引为e.hash & (newCap - 1)的位置。
                            newTab[e.hash & (newCap - 1)] = e;
                        else if (e instanceof TreeNode)//如果节点e是TreeNode
                            // 如果e节点时红黑树的节点,则调用TreeNode的split()方法
                            // 由于红黑树的知识也是比较复杂,本篇中不做过多解释。这里只说明树的各类方法的作用。split()方法是拆分红黑树,以实现节点的重新映射。
                            ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                        else { // 如果e节点是链表中的节点,则实现链表的复制
                        
                            //链表的复制操作,即将旧表中的含有e节点的链表复制到新表中
                            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;
        }
        
        
        
    

    6 get()方法

    get()方法根据键值获取元素值.

        public V get(Object key) {
            Node<K,V> e;
            //查找键值为key的节点,查找成功返回value值,否则返回null。
            return (e = getNode(hash(key), key)) == null ? null : e.value;
        }
        
        final Node<K,V> getNode(int hash, Object key) {
            Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
            
            //检查集合不为空,将first指向第一个节点
            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) {
                    // 如果节点e类型为红黑树的节点类型,则调用getTreeNode()方法返回节点。getTreeNode()方法是完成红黑树的查找操作。
                    if (first instanceof TreeNode)
                        return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                        
                    // 如果节点e为普通类型的节点,则遍历链表查找
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key || (key != null && key.equals(k))))
                            return e;
                    } while ((e = e.next) != null);
                }
            }
            //没有查找到返回null
            return null;
        }
        
        
    

    7 contains()方法

    //判断是否包含键key
    public boolean containsKey(Object key) {
    //同样采用getNode方法进行查找,查找结果不为null则说明存在
    return getNode(hash(key), key) != null;
    }
    //是否包含value
    public boolean containsValue(Object value) {
    Node<K,V>[] tab; V v;
    if ((tab = table) != null && size > 0) {
    for (int i = 0; i < tab.length; ++i) {
    for (Node<K,V> e = tab[i]; e != null; e = e.next) {
    if ((v = e.value) == value ||
    (value != null && value.equals(v)))
    return true;
    }
    }
    }
    return false;
    }

    8 remove()方法

     @Override
        public boolean remove(Object key, Object value) {
            return removeNode(hash(key), key, value, true, true) != null;
        }
        
        //删除节点
        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)
                        // 查找到的节点属于数组table中的元素,则直接将tab中的元素重新赋值
                        tab[index] = node.next;
                    else
                        //链表的节点赋值
                        p.next = node.next;
                    ++modCount;
                    //更新数目
                    --size;
                    afterNodeRemoval(node);
                    return node;
                }
            }
            return null;
        }
        
    

    9 小结

    HashMap采用数组+链表的方式存储键值对,当链表长度超过限定阈值,则将链表结构调整为红黑树,提高查找效率。通过源码可以看出在添加键值对时没有null检查,因此HashMap是允许null值的。

    10 对比

    1) HashMap允许将null作为一个entry的key或者value,而Hashtable不允许。
    2) 由于HashMap非线程安全,Hashtable是线程安全的。
    3)HashMap增加了红黑树。
    
  • 相关阅读:
    fancybox 基础 简单demo
    fancybox 最基本的使用步骤
    数组元素循环右移问题
    Python爬虫学习(8):浙大软院网络登陆保持
    Python爬虫学习(7):浙大软院网号嗅探
    Python爬虫学习(6): 爬取MM图片
    Python爬虫学习(5): 简单的爬取
    Python爬虫学习(4): python中re模块中的向后引用以及零宽断言
    Python爬虫学习(2): httplib
    Windows远程连接CentOS桌面
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13308030.html
Copyright © 2020-2023  润新知