【HashMap源码分析】---- 源代码注释逐行分析

注意注意,hashmap里的红黑树的节点是node的一个子类,所以这个树节点也可以使用next,在构建数时他的next指针会保留,当需要的时候仍可以使用。

TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
Entry<K,V> extends HashMap.Node<K,V>
package java.util;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
@jdk8

jdk1.2引入

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

序列化ID
private static final long serialVersionUID = 362498820763181265L;
初始容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
最大容量2^30
static final int MAXIMUM_CAPACITY = 1 << 30;
默认负载因子(当hashmap中容量打到 负载因子当前容量时,扩容为当前容量2)
static final float DEFAULT_LOAD_FACTOR = 0.75f;
一个桶链表变换乘红黑树的临界值 不能小于2
static final int TREEIFY_THRESHOLD = 8;
红黑树退化成链表的临界值
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;
key value 在hashmap中的存储形式
static class Node<K,V> implements Map.Entry<K,V> {
hash值
final int hash;
key值
final K key;
value值
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;
        }

Entry中getKey
public final K getKey() { return key; }
Entry中getValue
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
计算哈希码 key的hash异或value的hash
public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); }
更改value,并返回原来的value
public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; }
先判断地址,如果地址不同判断类型和key,value

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

??为啥要这么算有空再查查。

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

如果该类实现了Comparable了 返回x的class对,否则返回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.((Comparable)k).compareTo(x)) 否则返回0

    @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 = -1,0 1 —> n = 1
cap = 2 —> n = 2
cap = 3,4 —> n = 4
cap = 5,6,7,8 —> 8
cap = 9,10,11,12,13,14,15,16—> 16

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

这应该就是哈希”表”了吧
transient Node<K,V>[] table;
所有的entry
transient Set<Map.Entry<K,V>> entrySet;
目前的size
transient int size;
iterator中用来防止篡改的
transient int modCount;
capacity * loadfactor
int threshold;
当前负载因子
final float loadFactor;
构造函数 如果initialCapacity 不是2^n 会向上进位

    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);
    }
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

将一个map加入到这个hashmap中 evict??,看看下面putVal咋实现的

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

size O(1)
public int size() { return size; }
isEmpty O(1)
public boolean isEmpty() { return size == 0; }
根据key返回val 时间复杂度取决于下面的getNode

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

第一个node的地址为(n – 1) & hash
首先判断第一个节点与要找的key一样不一样

  • 判断的过程:先==,后equals

然后判断该桶里时红黑树还是链表,然后根据对应的规则进行搜索

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

containskey通过getNode来实现

    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

put没啥说的调用putVal

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
  1. 首先判断实例中是否以及存在表了,如果不存在,通过resize创建一个Node数组
  2. 然后通过传入的key的【hash&(n -1)】计算索引查找所在的桶内是否以及存在元素了,
  3. 如果没有元素在这个桶里,根据传入的kv创建桶的头结点
    1. ++modCount;
    2. size++
    3. 判断是够扩容
    4. afterNodeInsertion(evict);
  4. 如果桶内已经存在元素了
    1. 如果发现桶内的头结点key与传入的key的值地址相同,或者key equals k, 令e等于当前节点
    2. 如果该桶已经进化成红黑数了,利用红黑树的api进行插入或者更新 e等于返回的节点
    3. 否则,向链表后面走,并更新e为当前节点,如果找到了与key对应的节点 p=e,如果没找到就在最后没新建一个,此时若发现打到了进化红黑树的阀值,将此链表进化
    4. 如果e中val为空插入val,不为空 根据onlyIfAbsent判断是否更新,如果false—更新,true—不更新e—
  • 执行 afterNodeAccess(e);
    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;
            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;
    }

如果之前有实例中有table已经初始化并且桶数大于8 扩容2倍后小于2^30,进行扩容,并更新thr
如果之前table为空,

  • 但oldThr有值,cap = oldThr,并更新thr
  • 如果oldThr等于0,cap = 0,thr = DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY
    根据新的容量新建一个数组,原来的顺序会被打乱,甚至一个桶内的元素会被散列到不同位置去,并将老数组的每一个位置更新为null,便于垃圾回收
 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;
    }

把链表替换成红黑树,这个算法有空可以看一下

    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 {
                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复制到实例中,如果key存在会覆盖掉之前的值
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;
    }

基本思路与put类似,然后先找到节点,然后删除

    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)
                    tab[index] = node.next;
                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;
        }
    }

判断包含value
这里有的桶里已经时红黑树了,但是仍用next去寻找

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;
    }
    原文作者:qming_c
    原文地址: https://www.jianshu.com/p/3a8b054f093e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞