HashMap源码浅读



首先要知道java8中HashMap由数组(bucket)、链表、红黑树这3种数据结构组成


下面就从源码分析理解HashMap~GO
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     //初始数组容量(桶的数量),默认为16,并且总是2的幂方
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    //最大数组容量,如果new HashMap时指定CAPACITY超过此限制则默认为最大值
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //负载因子默认为0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //当一个桶上的链表长度>=8时,链表转化为红黑树
    static final int TREEIFY_THRESHOLD = 8;
    //当链表长度<6时红黑树转化为链表
    static final int UNTREEIFY_THRESHOLD = 6;
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    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;
    }


    }

    Java8HashMap不同Java7,8中节点是由Node对象实现,而7中则是Entry。上述是在HashMap定义了静态Node类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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;
    }

    这是Node重写的equals方法,说明判断2个节点相等要Key和Value都相等。

  • 1
    2
    3
    4
    static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    HashMap结合元素自身的hashcode以及再hash的方式来获取元素的哈希值,在通过取模的方式映射到数组中,其中取模运算是通过优化后的位运算来实现的。

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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);
    }

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

    /**
    * 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
    }
    HashMap重载的3个构造器
  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    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) {
    //变量说明:tab用于存储table引用,first用于存储数组中第一个节点,e为目标节点
    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) {
    //比较key的hash值和key的值
    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;
    }

    上述是常用的get(Object key)方法,核心是getNode()方法,从源码可得知方法先用hash()算出key的值在找到数组中对应的位置,在判断节点的类型,调用不同的方法进行处理。在匹配key时不仅要hash值相等,key的值也要相等,这也验证了hashCode()和equals()返回的结果要相等。

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    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;
    //检测数组是否为空,如果为空则调用resize()进行扩容初始化
    if ((tab = table) == null || (n = tab.length) == 0)
    n = (tab = resize()).length;
    //通过hash找到桶的位置判断是否有节点存在,若无则直接newNode
    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;
    }
    }

    //对匹配成功的节点进行值的更新
    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;
    }

    上述就是整个put操作的逻辑。

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    final Node<K,V>[] resize() {
    Node<K,V>[] oldTab = table;
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
    int oldThr = threshold;
    int newCap, newThr = 0;
    //更新新table的容器大小,
    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指向新的table
    table = newTab;
    if (oldTab != null) {
    //把oldtab的节点移到newtab上
    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)
    //如果是红黑树结构,转向split
    ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
    else { // preserve order
    //如果是链表
    Node<K,V> loHead = null, loTail = null;//记录在newtab下位置也是j的节点
    Node<K,V> hiHead = null, hiTail = null;///记录在newtab下位置是j + oldtab的节点
    Node<K,V> next;
    do {
    next = e.next;
    if ((e.hash & oldCap) == 0) {
    //如果该节点的(e.hash & oldCap) == 0,说明(e.hash & newCap - 1) == j
    if (loTail == null)
    loHead = e;
    else
    loTail.next = e;
    loTail = e;
    }
    else {
    //否则就是(e.hash & newCap - 1) =j + oldtab
    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;
    }

    上述代码中最核心的部分即为对扩容后的数组的重建,不同于Java7中数组的构建(头插法),Java8采用了尾插法,保证了新构建的数组与原数组在碰撞后的元素组织次序的一致。同时还需要注意的是,HashMap不通过线程安全的支持,因此在数组扩容的过程中会造成死循环。多线程下最好还是使用ConcurrentHashMap

抽空更新┗|`O′|┛ 嗷~~

等你, 在雨中, 在造虹的雨中!