Java集合004 --- HashMap部分源码及原理

前言

HashMap是一个用来存储<key,value>对的集合,允许key和value为null,并且无序;

内部实现JDK1.7和JDK1.8略有不同,1.7内部实现用的是数组+单链表,而1.8内部实现是数组+链表+红黑树;

HashMap实现了Cloneable、Serializable、Map接口

属性 

// 桶的个数或者数组的初始容量
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;

// 去树化阈值, 将红黑树转换为链表
static final int UNTREEIFY_THRESHOLD = 6;

// 最小树化阈值, 当数组节点个数大于等于64时, 转换成红黑树
static final int MIN_TREEIFY_CAPACITY = 64;

// 用来存储HashMap中的元素
transient Node<K,V>[] table;

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

// HashMap元素个数
transient int size;

// 修改次数
transient int modCount;

// 需要扩容的容量( capility * loadFactor )
int threshold;

// 负载因子
final float loadFactor;

构造器啥的就不详细说了,直接说比较重要的put和get方法

put方法

put方法用来向HashMap中插入元素,并且是无序的,put方法流程为:

1、计算key的hash值,计算方法为key的hashcode与hashcode高16位的异或值

2、计算出key在HashMap数组中的索引,计算方法为:key的hash值与当前数组长度减一做按位与

 为啥要这样做呢?这是因为在1.7中底层结构是数组+链表,如果获取hash值不做特殊处理的话,会导致命中数组索引概率很高,

 进而导致链表元素个数很多;我们知道链表的遍历时间复杂度为O(n),n很大时,查询非常耗时;因此在1.8中使用异或和按位与

 对计算hash做了优化,能够降低数组索引的命中率;这是在1.8中的一个优化点

3、数组为空,设置容量为默认容量16,负载因子0.75

4、未命中数组索引,创建新的节点,然后放置在当前索引位置

5、直接命中数组索引,并且key、key的hash和equals方法均判等,则覆盖原节点的值

6、否则,先判断命中的节点是否为红黑树节点,如果是,将新节点插入到红黑树

7、命中节点为树节点,将节点插入到链表后,如果链表节点数大于等于默认树化阈值8,并且数组节点个数大于等于最小树化阈值64,则将链表转换为红黑树

8、这又是1.8的另一个优化点:红黑树的遍历时间复杂度为O(logn),低于链表的O(n)

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)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        // 直接命中, 并且key、hash和equals判等, 直接覆盖元素
        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);
                    // 链表个数大于等于树化阈值8&桶的个数大于等于树化阈值64, 转换为红黑树
                    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;
}

get方法

public V get(Object key) {
    Node<K,V> e;
    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;
    // 数组不为空, 并且直接命中
    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使用时注意事项

阿里开发手册中建议在创建HashMap时,按照业务需求指定容量,如果不超过16设置成16;

原因:HashMap容量不足时,会进行扩容,容量增加到原来容量的两倍;但是扩容的过程是创建新的数组,然后将原来的数组映射到新数组,这会有很大的内存损耗;

那么是不是业务量是多少指定多少就可以呢?也就是HashMap(7)的容量会是7么?答案为否,真正的初始容量为8,原因是:HashMap在确定初始容量时会按照输入数值向上找最近的2次幂,源码如下:

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);
}
// 位运算, 计算输入向上最接近的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;
}

HashMap的扩容机制

当插入元素,并size自增后,判断当前元素个数是否超过容量*负载因子,因此初始容量应指定为(exceptedSize/(loadFactor + 1))

如果需要精确指定容量大小,可以使用Guava库中的Maps.newHashMapWithExceptedSize()方法                      

原文地址:https://www.cnblogs.com/sniffs/p/12961499.html