HashMap

156 阅读12分钟

定义

Map是一个接口,Map中以键值对方式存储数据((K key,V value)),其中键和值是一对一映射关系,可以通过键来获取值。基本方法使用参照

HashMap是Map接口的一个实现类。(底层实现JDK<=1.7数组+链表,JDK>=1.8数组+链表+红黑树)基本方法使用参照

new HashMap()

我们需要了解一下Map map = new HashMap()和HashMap map = new HashMap()的区别。

1、Map map = new HashMap(),就是将map实例化成一个HashMap。这样做的好处是调用者不需要知道map具体的实现,具体实现的映射java帮你做了。这个其实你定义的是一个接口,你调用这个接口来实现你要完成的动作,这样别人直接用你这个接口就可以了,而不用关心你具体是怎么实现这个接口的,假如以后有变动的话,你不用在去管这个接口,只去改下你的实现类就可以了,方便维护,隔离性强。这种方式更符合接口式编程规范,即只需要关心实现哪些动作,而不用关心具体怎么去实现。

2、HashMap map = new HashMap(),这种方式定义的就是一个实现类,你把这个实现类给别人用,在出现问题和改动的话,那么程序就无法运行,凡是用到这个类的地方都要修改,维护起来很麻烦,而上面的接口,你只需要改你实现这个接口的实现类就可以了。

所以在实际开发中,我们更倾向于使用第一种方式。

初始化

HashMap.jpg

1、初始化时不设置容量大小(不设置大小时,HashMap的默认初始长度(即table容量)是16,自动拓展和手动初始化时,长度必须是2的幂,即2^n (每次扩容都是以2的整数次幂扩容))

原因:选择16是为了服务于从Key映射到index的hash算法,在性能和内存的使用上取平衡,实现一个尽量均匀分布的Hash函数,选取16是通过位运算的方法进行求取的。(hash算法,放到下面阐述)

Map<String, String> map = new HashMap<>();

对应源码如下:

/**
 * Constructs an empty <tt>HashMap</tt> with the default initial capacity
 * (16) and the default load factor (0.75).
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

此时只会加载默认负载因子,容量,阈值,table均不初始化。

2、初始化时设置容量大小

Map<String, String> map = new HashMap<>(8);
/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and the default load factor (0.75).
 *
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

或者

Map<String, String> map = new HashMap<>(8, (float) 0.5);

对应源码如下:

/**
 * Constructs an empty <tt>HashMap</tt> with the specified initial
 * capacity and load factor.
 *
 * @param  initialCapacity the initial capacity
 * @param  loadFactor      the load factor
 * @throws IllegalArgumentException if the initial capacity is negative
 *         or the load factor is nonpositive
 */
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);
}
/**
 * Returns a power of two size for the given target capacity.
 */
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;
}

当初始化传入一个数字a的时候,HashMap会找出第一个大于等于a的2n次幂数,然后赋值给阈值。例如,如果a大于8小于等于16,那么阈值都是16。注意:此时table是空的,还没有初始化,获取capacity会返回阈值。即初始化时设置容量,会初始化负载因子和阈值,容量和table均不初始化。

由此可以看出在初始化时,是不会初始化table的。而table的初始化是放在了put操作中。

hash计算和寻址

在讨论table的初始化之前,应当先了解底层如何寻址以及如何求hash

1、寻址(这里讨论jdk1.8优化后的算法,原本的算法是hash % n)

tab[i = (n - 1) & hash]),用来计算当前 key 存储的位置,并获取当前存储位置的元素,进行后续的判断。

2、hash计算

/**
 * Computes key.hashCode() and spreads (XORs) higher bits of hash
 * to lower.  Because the table uses power-of-two masking, sets of
 * hashes that vary only in bits above the current mask will
 * always collide. (Among known examples are sets of Float keys
 * holding consecutive whole numbers in small tables.)  So we
 * apply a transform that spreads the impact of higher bits
 * downward. There is a tradeoff between speed, utility, and
 * quality of bit-spreading. Because many common sets of hashes
 * are already reasonably distributed (so don't benefit from
 * spreading), and because we use trees to handle large sets of
 * collisions in bins, we just XOR some shifted bits in the
 * cheapest possible way to reduce systematic lossage, as well as
 * to incorporate impact of the highest bits that would otherwise
 * never be used in index calculations because of table bounds.
 */
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

如上,hash算法是对象key值的(hashCode)异或(hashCode右移16位),右移16位,进行异或运算。为何要做这种优化,has算法是hash & (n - 1),由于(n-1)的二进制值的高16位大概率都是0(n是hashMap的大小,不太可能超过2的16次方),为了让hash值的高16位参与运算,所以hash算法中将hash值的高16位和低16位进行了异或运算,使得高低16位都参与了hash计算,减少hash碰撞的概率。

put方法和resize()(扩容)方法

我们看HashMap类中的put方法源码

    return putVal(hash(key), key, value, false, true);
}
  /**
     *
     * @param hash         指定参数key的哈希值
     * @param key          指定参数key
     * @param value        指定参数value
     * @param onlyIfAbsent 如果为true,即使指定参数key在map中已经存在,也不会替换value
     * @param evict        如果为false,数组table在创建模式中
     * @return 如果value被替换,则返回旧的value,否则返回null。当然,可能key对应的value就是null。
     */
   public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
 
// 参数解析:onlyIfAbsent表示,如果为true,那么将不会替换已有的值,否则替换
// evict:该参数用于LinkedHashMap,这里没有其他作用(空实现)
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
    // tab是该方法中内部数组引用,p是数组中首节点,n是内部数组长度,i是key对应的索引下标
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    // 第一次put的时候,table未初始化,也就是tab为空,需要扩容
    if ((tab = table) == null || (n = tab.length) == 0)
    	// 这里实现扩容,具体逻辑稍后分析
        n = (tab = resize()).length;
    // 获取指定key的对应下标的首节点并赋值给p,如果首节点为null,那么创建一个新的Node节点作为首节点
    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))))
            // p此时指向的是不为null的首节点,将p赋值给e
            // 如果首节点的key和要存入的key相同,那么直接覆盖value的值(在下一个if中执行的)
            e = p;
        else if (p instanceof TreeNode)
        	// 如果首节点是红黑树的,将键值对插添加到红黑树,该方法后续分析
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
        	// 能走到这里,说明首节点和新put的的这个节点的key不一样,且该Node节点不是TreeNode类型
        	// 开始需要遍历链表,如果链表中存在该键值对,直接覆盖value。
        	// 如果不存在,则在末端插入键值对。然后判断链表长度是否大于等于8(其实就是遍历次数 + 1),
        	// 尝试转换成红黑树。注意此处使用“尝试”,因为在treeifyBin方法中还会判断
        	// 当前哈希表长度是否到达64,如果达到,转换为红黑树,否则会放弃次此转换,优先扩充数组容量。
            for (int binCount = 0; ; ++binCount) {
            	// 当binCount = 0时,也就是第一次if判断,此时p就是首节点,p.next就是第二个节点
            	// 其他情况及时链表中其他节点,当e == null的时候,也就是到达了链表的结尾
                if ((e = p.next) == null) {
                	// 新建一个Node并作为链表的最后一个节点
                    p.next = newNode(hash, key, value, null);
                    // 判断遍历次数是否>=7(首节点未遍历,直接从第二个节点开始遍历的,当次数为7时,说明链表长度为8)
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                    	// “尝试”将链表转换为红黑树,内部还会判断哈希表长度,不一定转换成功,也许是扩容
                        treeifyBin(tab, hash);
                    break;
                }
                // 只要没走到上面那个if里面,说明链表没有遍历结束,如果在链表中间发现有key一样的,那么就直接将旧值替换成新值
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                // 将正在遍历的节点赋值给p,方便能遍历下一个节点
                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;
}
 
//链表转化为红黑树的方法
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 {
        	// 将链表中的节点Node类型转换成为TreeNode
            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);
        // TreeNode链表转换成为红黑树
        if ((tab[index] = hd) != null)
            hd.treeify(tab);
    }
}

流程图如下:

GVDIjAhSLl.jpg

其中链表转换成红黑树是有标准的:

当哈希表的中链表元素超过8个的时候(此时哈希表长度不小于64),会自动转换成红黑树。若元素小于等于6时,树结构还原成链表形式。

红黑树的平均查找长度是log(n),长度为8,查找长度为log(8)=3,链表的平均查长度为n/2,当长度为8时,平均查找长度为8/2=4,这才有转换成树的必要;链表长度如果是小于等于6,6/2=3,虽然速度也很快的,但是转化为树结构和生成树的时间并不会太短。以6和8来作为平衡点是因为,中间有个差值7可以防止链表和树之间频繁的转换。

假设,如果设计成链表个数超过8则链表转换成树结构,链表个数小于8则树结构转换成链表,如果一个HashMap不停的插入、删除元素,链表个数在8左右徘徊,就会频繁的发生树转链表、链表转树,效率会很低。概括起来就是:链表:如果元素小于8个,查询成本高,新增成本低,红黑树:如果元素大于8个,查询成本低,新增成本高。

而由上我们可以看到,在put方法中有两种情况会进入resize()方法:

1.table没有初始化或者容量为0时

2.table已使用容量超过阈值

然后我们看下resize源码

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

然后可以看到有三种情况:

1、旧容量不为0时,新容量更改为旧容量的2倍

2、旧容量为0,但是旧阈值不为0时,新容量等于旧阈值

3、旧容量和旧阈值都为0,新容量为默认的16,新阈值为默认的16*0.75=12

多线程中的安全性(仍以jdk1.8来讨论)

在jdk1.8中,HashMap仍然线程不安全,jdk1.8在扩容时采用的时尾插法。

结合上面put方法源码流程看,我们可以发现

1、在判断是否发生hash冲撞的时候会出现问题:

假设两个线程A、B都在进行put操作,并且hash函数计算出的插入下标是相同的,当线程A执行完判断是否发生hash冲撞后由于时间片耗尽导致被挂起,而线程B得到时间片后在该下标处插入了元素,完成了正常的插入,然后线程A获得时间片,由于之前已经进行了hash碰撞的判断,所有此时不会再进行判断,而是直接进行插入,这就导致了线程B插入的数据被线程A覆盖了,从而线程不安全。

2、在判断++size的时候会出现问题:

假设线程A、B,这两个线程同时进行put操作时,假设当前HashMap的zise大小为10,当线程A执行到++size时,从主内存中获得size的值为10后准备进行+1操作,但是由于时间片耗尽只好让出CPU,线程B快乐的拿到CPU还是从主内存中拿到size的值10进行+1操作,完成了put操作并将size=11写回主内存,然后线程A再次拿到CPU并继续执行(此时size的值仍为10),当执行完put操作后,还是将size=11写回内存,此时,线程A、B都执行了一次put操作,但是size的值只增加了1,所有说还是由于数据覆盖又导致了线程不安全。