Java集合(八)HashMap详解

本文详细剖析了HashMap的工作原理,包括其内部结构、构造方法、存储和获取机制,以及扩容过程。探讨了不同版本JDK中HashMap数据结构的变化,尤其是在JDK1.8中引入红黑树以提高性能的关键改进。

  其实关于HashMap的总结文字已经在笔记中存放很久,因为在做分析时,Map与让我们又爱又恨的数据结构关联非常紧密。以至于心底燃起的学习火焰欲罢不能,所以又去从头看了两本数据结构的书。一本是程杰老师的大话数据结构,另一本是很经典的数据结构与算法,也算受益良多。废话不多说,还是一起来学习HashMap吧。

散列表

简介

  散列技术是在记录的存储位置和它关键字之间建立一个确定的对应关系 f ,使得每个关键 key 对应一个存储位置 f (key)。
  这里我们把这种对应关系 f 称为散列函数,又称为哈希(Hash)函数。按这个思想,采用散列技术将记录存储在一块连续的存储空间中,这块连续存储空间称为散列表或哈希表(Hash table)。
  举个例子。假如我们有十个仓库,然后将货物都编上号码,如果货物个位是0,就放到0号仓库,个位是1,就放到1号仓库。这样,我们就建立了一个货物编号与仓库之间的对应关系:
  f(id) = id % 10
  这种哈希函数一般称为除留余数法,当然还有其他的构造方法。这不是一个重要的知识点,这里便不再介绍了。

处理冲突

  还是考虑仓库的例子。如果我们已经把3号货物送到了3号仓库,这时我们想从仓库中取出3号货物送到了3号仓库,这时我们想从仓库中取出3号货物,就非常简单,只要直接去3号仓库中去取就好了。我们考虑使用代码来表示,用一个数组代表仓库

 int[] warehouse = new int[10];
复制代码

  那么,往里面存数据的函数就可以写成:

    int hash(int id) {
        return id % 10;
    }

    void put(id) {
        warehouse[hash(id)] = id;
    }
复制代码

  当插入的数据是11,14,26,45,39时,一切都非常好,所有的货物都能找到自己对应的仓库。但如果这时,又来了一个21,31,就有问题了。这时就会发现,1号仓库已经被11占据了。这种情况就是发生了冲突。
  选择一个更加均匀的哈希函数可以减少冲突,但不能完全避免,所以如果处理冲突是哈希表不可缺少的一方面。
  解决冲突的方法有很多,比如:

  • 开放定址法
  • 再散列函数法
  • 链地址法
  • 公共溢出区法
      今天介绍一下链地址法。其他的也不再细说。链地址法的思路非常简单,就是把原来容量为1的仓库,变成一个单链表就可以了,看下面的图:

HashMap

概述

  HashMap是基于哈希表的Map接口实现的,每一个元素都是一个 kay-value 对,其内部通过单链表解决冲突问题,容量不足时,同样会自动增长。
  这种实现提供所有可选的映射操作,并允许使用 null 键和 null 值。除了不同步和允许使用null之外,HashMap类与Hashtable基本相同。该类不保证有序(如插入顺序)、也不保证序不随时间变化。
  非线程安全,可通过Collections类的静态方法synchronizedMap获取线程安全的HashMap。或者使用ConcurrentHashMap。
  实现了Cloneable接口,可进行拷贝,实现的是浅层次拷贝,即:对拷贝对象的改变会影响被拷贝的对象。实现了Serializable接口,可实现序列化,可将HashMap对象保存至本地,之后可恢复状态。

HashMap源码分析

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

    private static final long serialVersionUID = 362498820763181265L;

    //默认的初始容量是16-实际容量必须是2的整数次幂
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    //最大容量(必须是2的幂且要小于2的30次方,传入容量过大将被这个值替换)
    static final int MAXIMUM_CAPACITY = 1 << 30;

    //默认加载因子为0.75(加载因子:HashMap在其容量自动增加前可达到多满的一种尺度)
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 与红黑树相关的参数
     */
    //桶的树化阈值
    //链表转成红黑树的阈值,在存储数据时,当链表长度>该值时,就将链表转换为红黑树
    static final int TREEIFY_THRESHOLD = 8;

    //桶的链表还原阈值
    //红黑树转换为链表的阈值,当扩容 resize() 时,HashMap的数据存储位置会重新计算
    //在重新计算存储位置后,当原有的红黑树内数量< 6时,就将红黑树转换为链表
    static final int UNTREEIFY_THRESHOLD = 6;

    //最小树形化容量阈值
    //当哈希表中的容量 > 该值时,才允许树形化链表(将链表转换成红黑树)
    //否则,若桶内元素太多时,则直接扩容,而不是树形化
    //为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
    static final int MIN_TREEIFY_CAPACITY = 64;

    /**
     * Node是HashMap的内部类,实现了Map.Entry接口,本质是一个映射(键值对)
     * 实现了getKey()、getValue()、equals(Object o)和hashCode()等方法
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; //哈希值,HashMap根据该值确定记录的位置
        final K key;    //key
        V value;    //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;
        }
    }

   //JDK 1.8 实现:将键key 转换为哈希值操作 = 使用hashCode()+ 1次位运算 + 1次异或运算(2次扰动)
   //1.取hashCode值:h = key.hashCode() 2.高位参与低位的运算:h ^ (h >>> 16)
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        // a. 当key = null时,hash值 = 0,所以HashMap的key 可为null      
        // 注:对比HashTable,HashTable对key直接hashCode(),若key为null时,会抛出异常,所以HashTable的key不可为null
        // b. 当key ≠ null时,则通过先计算出 key的 hashCode()(记为h),然后 对哈希码进行 扰动处理: 按位 异或(^) 哈希码自身右移16位后的二进制
    }

    /**
     * 通过反射判断对象x是否实现Comparable<C>接口
     * @return 如果实现了Comparable,返回x的实际类型,也就是Class<C>,否则返回null. 
     */
    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    /** 
     * 如果x实际类型是kc,则返回k.compareTo(x),否则返回0 
     *  
     * @param kc 必须实现Comparable 
     * @param k 类型为kc 
     * @param x 类型无限制 
     */
    @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));
    }

    //返回不小于cap的最小的2的幂
    //作用:将传入的容量大小转化为:> 传入容量大小的最小的2的幂
    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;
    }

    //存储数据的Node类型(实际数据的存储结构,尺寸可能变更)
    transient Node<K,V>[] table;

    //entrySet()缓存
    transient Set<Map.Entry<K,V>> entrySet;

    //实际元素个数(HashMap的大小,HashMap中存储的键值对的数量)
    transient int size;

    //HashMap发生结构变更的计数器,结构变更包括增删元素、rehash等,实现迭代子的fast-fail特性
    transient int modCount;

    //扩容阈值:当哈希表的大小 >= 扩容阈值时,就会扩容哈希表(扩充HashMap的容量)
    //a.扩容 = 对哈希表进行resize操作(重建内部数据结构),从而哈希表将具有大约两倍的桶数
    //扩容阈值 = 容量*加载因子
    int threshold;

    //实际加载因子
    final float loadFactor;

    /* ---------------- public 方法 -------------- */

    /**
     * 指定“容量大小”和“加载因子”的构造方法
     * 加载因子和容量都是自己指定
     */
    public HashMap(int initialCapacity, float loadFactor) {
        //指定初始容量必须非负
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
                                               
        //HashMap的最大容量只能是MAXIMUM_CAPACITY,哪怕传入的 > 最大容量
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        //填充比必须为正
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        //设置加载因子
        this.loadFactor = loadFactor;
        //设置扩容阈值
        //注:此处不是真正的阈值,仅仅只是将传入的容量大小转化为:>传入容量大小的最小的2的幂,该阈值后面会重新计算
        this.threshold = tableSizeFor(initialCapacity);
    }

    /**
     * 指定容量大小的构造方法
     * 加载因子为默认的0.75,容量为指定大小
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 默认构造方法(无参)
     * 加载因子为默认0.75,容量为默认的16
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 包含“子Map”的构造方法
     * 构造出来的HashMap包含传入Map的映射关系。加载因子和容量都是默认
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        //加载因子和容量都是默认
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //将传入的子Map中的全部元素逐个添加到HashMap中
        putMapEntries(m, false);
    }

    /**
     * 将m的所有元素存入本HashMap实例中,实现Map.putAll的构造方法
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
            if (table == null) { // pre-size
                //根据m.size初始化threshold
                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)
                //如果m.size已经超过threshold,就立即resize
                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);
            }
        }
    }

    //返回哈希表中所有键值对的数量 = 数组中的键值对 + 链表中的键值对
    public int size() {
        return size;
    }

    //判断HashMap是否为空,即无键值对;size == 0时 表示为 空 
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 根据键key,向HashMap获取对应的值
     */
    public V get(Object key) {
        Node<K,V> e;
        //1.计算需获取数据的hash值
        //2.通过getNode()获取所查询的数据
        //3.获取后,判断数据是否为空
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * 通过key获取所查询的数据
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //计算存放在数组table中的位置
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            
            //通过该方法,一次在数组、红黑树、链表中查找(通过equals()判断)
            //先在数组中找,若存在,就直接返回
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
                
            //若数组中没有,就到红黑树中寻找
            if ((e = first.next) != null) {
                //在树中get
                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;
    }

    /**
     * 判断是否存在该键的键值对;是 则返回true
     * 原理:调用getNode(),判断是否为null
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

    /**
     * 向HashMap添加数据
     */
    public V put(K key, V value) {
        //1.对传入数组的键key计算Hash值
        //2.再调用putValue()添加数据进去
        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;
        
        //1.如果哈希表的数组tab为空,则通过resize()创建
        //因此,初始化哈希表的时机就是第一次调用put方法的时候,调用resize()初始化创建
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        
        //2.计算插入存储的数组索引i:根据键值key计算的hash值得到
        //插入时,需判断是否存在Hash冲突
        //不存在(当前table[i] == null),就直接在该数组位置新建节点,插入完毕
        //如果存在Hash冲突,即当前存储位置已经存在节点,便依次判断:
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            
            //3.判断table[i]的元素的key是否与需插入的key一样,若相同就直接将新value覆盖旧value
            //判断原则:equals()
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            
            //4.继续判断:需插入的数据结构是否为红黑树或链表
            //4.1.如果是红黑树,就直接在树中插入或更新键值对
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                
            //4.2.如果是链表,就在链表中插入或者更新键值对
            else {
                //遍历table[i],判断key是否已存在
                //采用equals() 对比当前遍历节点的key 与需插入数据的key
                for (int binCount = 0; ; ++binCount) {
                    //如果不存在,则直接在链表尾部插入数据
                    if ((e = p.next) == null) {
                        //若数组的下1个位置,表示已到表尾也没有找到key值相同节点,则新建节点 = 插入节点
                        p.next = newNode(hash, key, value, null);
                        
                        //插入节点后,如果链表节点 > 树阈值,就将链表转换为红黑树
                        //判断链表长度是否>8(8 = 桶的树化阈值)
                        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指向下一个节点,继续遍历
                    p = e;
                }
            }
            
            //若已存在,则直接用新value 覆盖 旧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;
        
        //插入成功后,判断实际存在的键值对数量size > 最大容量threshold
        //如果大于,就进行扩容
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);//插入成功时会调用的方法(默认实现为空)
        return null;
    }

    /**
     * 扩容
     * 该方法有2种使用情况:1.初始化哈希表 2.当前数组容量过小,需扩容
     */
    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;
            }
            
            //如果没有超过最大值,就扩充为原来的2倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // 通过右移扩充2倍
        }
        
        //初始化哈希表(采用指定或者默认值)
        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);
        }
        
        //计算新的resize上限
        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) {
            //把每个bucket都移动到新的buckets中
            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 & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                        
                    else { //链表优化hash的代码块
                        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;
                            }
                            //原索引 + oldCap
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        //原索引放到bucket里
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        //原索引 + oldCap放到bucket里
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

    /**
     * 将桶内所有的链表节点替换成红黑树节点
     */
    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) {
            //如果哈希表中的元素个数超过了树形化阈值,进行树形化
            //e代表哈希表中指定位置桶里的链表节点,从第一个开始
            
            TreeNode<K,V> hd = null, tl = null;//红黑树的头、尾节点
            do {
                //新建一个树形节点,内容和当前链表节点e一致
                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);
        }
    }

    //将指定Map中的键值对复制到此Map中
    public void putAll(Map<? extends K, ? extends V> m) {
        putMapEntries(m, true);
    }

    //删除该键值对
    public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

    /**
     * 删除节点
     * @删除成功返回被删的元素,否则返回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;
            //根据key的hash值找到对应位置的链表
            //如果链表的第一个元素的key和要删除元素的key不一致,说明没有找到,继续往后找
            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;
                //如果找到的节点不是链表的第一个节点,那么此时p是node的前一个节点
                //那么直接通过p.next = node.next跨过node节点,达到删除效果
                else
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

    //清除哈希表中的所有键值对
    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0;
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null;
        }
    }

    //判断是否存在该值的键值对,这个方法要遍历全表
    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;
    }

    //获得key的Set集合
    public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new KeySet();
            keySet = ks;
        }
        return ks;
    }

    /** 
    * keySet实现内嵌类,基于HashMap本身的。并不是全功能的Set。 
    */
    final class KeySet extends AbstractSet<K> {
        public final int size()                 { return size; }
        public final void clear()               { HashMap.this.clear(); }
        public final Iterator<K> iterator()     { return new KeyIterator(); }
        public final boolean contains(Object o) { return containsKey(o); }
        public final boolean remove(Object key) {
            return removeNode(hash(key), key, null, false, true) != null;
        }
        public final Spliterator<K> spliterator() {
            return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
        }
        public final void forEach(Consumer<? super K> action) {
            Node<K,V>[] tab;
            if (action == null)
                throw new NullPointerException();
            if (size > 0 && (tab = table) != null) {
                int mc = modCount;
                // Android-changed: Detect changes to modCount early.
                for (int i = 0; (i < tab.length && modCount == mc); ++i) {
                    for (Node<K,V> e = tab[i]; e != null; e = e.next)
                        action.accept(e.key);
                }
                if (modCount != mc)
                    throw new ConcurrentModificationException();
            }
        }
    }
    
    //获得values的集合
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }
    
    /** 
    * Values实现内嵌类,基于HashMap本身的。
    */
    final class Values extends AbstractCollection<V> {
        ···
    }

    //获得键值对的集合
    public Set<Map.Entry<K,V>> entrySet() {
        Set<Map.Entry<K,V>> es;
        return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
    }

     /** 
    * EntrySet实现内嵌类,基于HashMap本身的。
    */
    final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        ···
    }

    // java8 的Map default方法的重写

    @Override
    public V getOrDefault(Object key, V defaultValue) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
    }

    @Override
    public V putIfAbsent(K key, V value) {
        return putVal(hash(key), key, value, true, true);
    }

    //key和value都匹配时删除
    @Override
    public boolean remove(Object key, Object value) {
        return removeNode(hash(key), key, value, true, true) != null;
    }

    //key和value都匹配时,替换为newValue 
    @Override
    public boolean replace(K key, V oldValue, V newValue) {
        Node<K,V> e; V v;
        if ((e = getNode(hash(key), key)) != null &&
            ((v = e.value) == oldValue || (v != null && v.equals(oldValue)))) {
            e.value = newValue;
            afterNodeAccess(e);
            return true;
        }
        return false;
    }
    
    //key存在时替换value
    @Override
    public V replace(K key, V value) {
        Node<K,V> e;
        if ((e = getNode(hash(key), key)) != null) {
            V oldValue = e.value;
            e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
        return null;
    }

    //带默认处理方式的get,如果key存在,则同get,否则就根据mappingFunction计算出value然后put 
    @Override
    public V computeIfAbsent(K key,
                             Function<? super K, ? extends V> mappingFunction) {
        if (mappingFunction == null)
            throw new NullPointerException();
        int hash = hash(key);
        Node<K,V>[] tab; Node<K,V> first; int n, i;
        int binCount = 0;
        TreeNode<K,V> t = null;
        Node<K,V> old = null;
        if (size > threshold || (tab = table) == null ||
            (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((first = tab[i = (n - 1) & hash]) != null) {
            if (first instanceof TreeNode)
                old = (t = (TreeNode<K,V>)first).getTreeNode(hash, key);
            else {
                Node<K,V> e = first; K k;
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) {
                        old = e;
                        break;
                    }
                    ++binCount;
                } while ((e = e.next) != null);
            }
            V oldValue;
            if (old != null && (oldValue = old.value) != null) {
                afterNodeAccess(old);
                return oldValue;
            }
        }
        V v = mappingFunction.apply(key);
        if (v == null) {
            return null;
        } else if (old != null) {
            old.value = v;
            afterNodeAccess(old);
            return v;
        }
        else if (t != null)
            t.putTreeVal(this, tab, hash, key, v);
        else {
            tab[i] = newNode(hash, key, v, first);
            if (binCount >= TREEIFY_THRESHOLD - 1)
                treeifyBin(tab, hash);
        }
        ++modCount;
        ++size;
        afterNodeInsertion(true);
        return v;
    }

    // 相当于回调方式的replace,如果key不存在不做处理。
    //key存在则根据remappingFunction算出新的value,如果为null,则删除,否则替换 
    public V computeIfPresent(K key,
                              BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        if (remappingFunction == null)
            throw new NullPointerException();
        Node<K,V> e; V oldValue;
        int hash = hash(key);
        if ((e = getNode(hash, key)) != null &&
            (oldValue = e.value) != null) {
            V v = remappingFunction.apply(key, oldValue);
            if (v != null) {
                e.value = v;
                afterNodeAccess(e);
                return v;
            }
            else
                removeNode(hash, key, null, false, true);
        }
        return null;
    }

    //全功能的compute
    //apply(k,null)表示k不存在的默认值回调 
    //apply(k,v)表示k存在的replace回调
    //apply()返回null表示删除节点 
    @Override
    public V compute(K key,
                     BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
        ···
    }

    // 与compute类似,不同是key存在的时候用apply(oldValue,value)来计算(BiFunction全部根据value来)
    @Override
    public V merge(K key, V value,
                   BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
        ···
    }

    //遍历处理所有元素
    @Override
    public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            // Android-changed: Detect changes to modCount early.
            for (int i = 0; (i < tab.length && mc == modCount); ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    //双参数版的forEach() 
    @Override
    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Node<K,V>[] tab;
        if (function == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    e.value = function.apply(e.key, e.value);
                }
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

    /* ------------------------------------------------------------ */
    // Cloning and serialization

    /**
     * 浅克隆,复制所有key-value的引用,不复制key-value本身的属性
     */
    @SuppressWarnings("unchecked")
    @Override
    public Object clone() {
        HashMap<K,V> result;
        try {
            result = (HashMap<K,V>)super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
        result.reinitialize();
        result.putMapEntries(this, false);
        return result;
    }

    // These methods are also used when serializing HashSets
    final float loadFactor() { return loadFactor; }
    final int capacity() {
        return (table != null) ? table.length :
            (threshold > 0) ? threshold :
            DEFAULT_INITIAL_CAPACITY;
    }

    /**
     *序列化
     */
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        int buckets = capacity();
        // Write out the threshold, loadfactor, and any hidden stuff
        s.defaultWriteObject();
        s.writeInt(buckets);
        s.writeInt(size);
        internalWriteEntries(s);
    }

    //反序列化
    private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        // Read in the threshold (ignored), loadfactor, and any hidden stuff
        s.defaultReadObject();
        reinitialize();
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new InvalidObjectException("Illegal load factor: " +
                                             loadFactor);
        s.readInt();                // Read and ignore number of buckets
        int mappings = s.readInt(); // Read number of mappings (size)
        if (mappings < 0)
            throw new InvalidObjectException("Illegal mappings count: " +
                                             mappings);
        else if (mappings > 0) { // (if zero, use defaults)
            // Size the table using given load factor only if within
            // range of 0.25...4.0
            float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
            float fc = (float)mappings / lf + 1.0f;
            int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                       DEFAULT_INITIAL_CAPACITY :
                       (fc >= MAXIMUM_CAPACITY) ?
                       MAXIMUM_CAPACITY :
                       tableSizeFor((int)fc));
            float ft = (float)cap * lf;
            threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                         (int)ft : Integer.MAX_VALUE);
            @SuppressWarnings({"rawtypes","unchecked"})
                Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
            table = tab;

            // Read the keys and values, and put the mappings in the HashMap
            for (int i = 0; i < mappings; i++) {
                @SuppressWarnings("unchecked")
                    K key = (K) s.readObject();
                @SuppressWarnings("unchecked")
                    V value = (V) s.readObject();
                putVal(hash(key), key, value, false, false);
            }
        }
    }

    /* ------------------------------------------------------------ */
    // iterators

    abstract class HashIterator {
        Node<K,V> next;        // next entry to return
        Node<K,V> current;     // current entry
        int expectedModCount;  // for fast-fail
        int index;             // current slot

        HashIterator() {
            expectedModCount = modCount;
            Node<K,V>[] t = table;
            current = next = null;
            index = 0;
            if (t != null && size > 0) { // advance to first entry
                do {} while (index < t.length && (next = t[index++]) == null);
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Node<K,V> nextNode() {
            Node<K,V>[] t;
            Node<K,V> e = next;
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            if ((next = (current = e).next) == null && (t = table) != null) {
                do {} while (index < t.length && (next = t[index++]) == null);
            }
            return e;
        }

        public final void remove() {
            Node<K,V> p = current;
            if (p == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            current = null;
            K key = p.key;
            removeNode(hash(key), key, null, false, false);
            expectedModCount = modCount;
        }
    }

    //遍历key
    final class KeyIterator extends HashIterator
        implements Iterator<K> {
        public final K next() { return nextNode().key; }
    }

    //遍历values
    final class ValueIterator extends HashIterator
        implements Iterator<V> {
        public final V next() { return nextNode().value; }
    }

    //遍历键值对
    final class EntryIterator extends HashIterator
        implements Iterator<Map.Entry<K,V>> {
        public final Map.Entry<K,V> next() { return nextNode(); }
    }

    /* ------------------------------------------------------------ */
    // spliterators
    //1.8新增 HashMap的spliterato基类
    static class HashMapSpliterator<K,V> {
        ···
    }

    //KeySpliterator
    static final class KeySpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<K> {
        ···
    }

    //ValueSpliterator
    static final class ValueSpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<V> {
        ···
    }

    //EntrySpliterator
    static final class EntrySpliterator<K,V>
        extends HashMapSpliterator<K,V>
        implements Spliterator<Map.Entry<K,V>> {
        ···
    }

    /* ------------------------------------------------------------ */
    // LinkedHashMap support 为LinkedHashMap预留的可重写的方法

    // Create a regular (non-tree) node 创建一个普通的Node
    Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
        return new Node<>(hash, key, value, next);
    }

    // TreeNode转为普通Node用 
    Node<K,V> replacementNode(Node<K,V> p, Node<K,V> next) {
        return new Node<>(p.hash, p.key, p.value, next);
    }

    // 根据key-value生成TreeNode,普通node转TreeNode  
    TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
        return new TreeNode<>(hash, key, value, next);
    }

    // 根据单个普通节点生成TreeNode 
    TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
        return new TreeNode<>(p.hash, p.key, p.value, next);
    }

    /**
     * 重置为空表,clonereadObject调用 
     */
    void reinitialize() {
        table = null;
        entrySet = null;
        keySet = null;
        values = null;
        modCount = 0;
        threshold = 0;
        size = 0;
    }

    // LinkedHashMap重写的回调 
    void afterNodeAccess(Node<K,V> p) { }
    void afterNodeInsertion(boolean evict) { }
    void afterNodeRemoval(Node<K,V> p) { }

    // 序列化表内容 
    void internalWriteEntries(java.io.ObjectOutputStream s) throws IOException {
        Node<K,V>[] tab;
        if (size > 0 && (tab = table) != null) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    s.writeObject(e.key);
                    s.writeObject(e.value);
                }
            }
        }
    }

    /* ------------------------------------------------------------ */
    // Tree bins

    /**
     * TreeNode.为LinkedHashMap而进行的扩展
     */
    static final class TreeNode<K,V> extends LinkedHashMap.LinkedHashMapEntry<K,V> {
    ···
    }

}

复制代码

总结

  关于HashMap的源码分析,给出以下几点重要的总结:
  1.从结构上我们可以知道,从JDK1.8开始,HashMap是数组+链表+红黑树实现的。而JDK1.7 HashMap的数据结构是数组+链表。做法是:当链表长度>8时,便将链表转换成红黑树。而引入红黑树,提高了HashMap的性能,因为这样可以解决哈希碰撞后链表过长而导致的索引效率慢的问题,这主要是利用了红黑树的快速增删改查的特点。
  2.HashMap共有四个构造方法。构造方法中都提到了两个很重要的参数:初始容量(initialCapacity)和加载因子(loadFactor)。这两个参数是影响HashMap性能的重要参数,其中容量表示哈希表中槽的数量(即哈希表的长度),初始容量是创建哈希表时的容量(从构造方法中可以看出,如果不指明,默认是16),加载因子是哈希表在其容量自动增加之前可以达到多满的一种尺度,当哈希表中的条目数超出了加载因子与当前容量的乘积(即扩容阈值threshold)时,就要对该哈希表进行扩容(resize)操作。
  3.HashMap工作原理:通过hash的方法,以及put和get存储和获取对象。存储对象时,我们首先将K/V传给put方法,它调用hashCode计算hash从而得到bucket位置,进一步存储,HashMap会根据当前bucket的占用情况自动调整容量(超过Load Facotr则resize为原来的2倍)。获取对象时,我们将K传给get,它调用hashCode计算hash从而得到bucket位置,并进一步调用equals()方法确定键值对。如果发生碰撞的时候,Hashmap通过链表将产生碰撞冲突的元素组织起来,在JDK1.8中,如果一个bucket中碰撞冲突的元素超过某个限制(默认是8),则使用红黑树来替换链表,从而提高速度。
  4.关于加载因子:加载因子是可以修改的。如果加载因子越大,填满的元素会越多,对空间的利用更充分,但是冲突的概率加大,链表变长,查找效率会降低;如果加载因子越小,那么冲突概率减小,链表变短,查找效率变高,但是填满空间会越少,会造成很多空间还没利用便开始扩容,对空间造成严重浪费,而且频繁的扩容会消耗性能。如果我们在构造方法中不指定,则系统默认加载因子为0.75,这是一个比较理想的值,一般情况我们不建议修改。
  5.关于扩容:扩容是一个相当耗性能的操作,因为需要重新计算元素在新的数组中的位置并进行复制处理。我们知道Java里的数组是无法自动扩容的,在通过源码分析resize()方法中,我们了解到HashMap便是使用一个容量更大的数组来代替已有的容量小的数组。新容量是原有容量的2倍。然后遍历旧数组的元素,重新计算出每个元素在新数组的存储位置,最后将旧数组的每个元素逐个转移到新数组中。所以,我们在用HashMap时,最好能提前预估HashMap中的元素个数,这样有助于提高HashMap的性能。
  6.HashMap是线程不安全的,其中一个重要原因是:多线程下容易出现resize()死循环,其本质是并发执行的put()操作导致触发扩容行为,从而导致环形链表,使得在获取数据遍历链表时形成死循环,即Infinite Loop。具体细节可以参考HashMap多线程死循环问题。因此,不要在并发的环境中同时操作HashMap,这种情况建议使用ConcurrentHashMap。

参考

Java 8系列之重新认识HashMap
Java集合:关于 HashMap 1.8 的重大更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值