HashMap 源码剖析

HashMap 源码剖析

1.hashmap的基本概念

  • hash的基本概念:把一个任意长度的基本输入,通过一系列的hash算法映射成一个固定长度的输出。有时候两个不同的输入,映射出一个相同的输出,这种情况呗称为hash冲突。
  • hashmap的存储结构按JDK8来说是:数组+链表+红黑树构成的。
    twI1bR.png
  • hashmap的每一个存储单元称为一个node结构。node中包含了:
    key字段:map中key的字段
    value字段:map中value的字段
    next字段:当发生hash冲突的时候,当前桶中的node与发生冲突的node形成编标要用到的字段
    hash字段:存储key的hash值,但是要经过一次扰动

2.hashmap类

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

3.hashmap基本属性

private static final long serialVersionUID = 362498820763181265L;//序列化版本号
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 初始化长度为16,切必须是2的N次方
static final int MAXIMUM_CAPACITY = 1 << 30;//最大的容量为2^30,一般用于自定义初始化容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认负载因子
static final int TREEIFY_THRESHOLD = 8;//数组单个单元要转化为红黑树节点的阈值
static final int UNTREEIFY_THRESHOLD = 6;//反树化时,节点的阈值
static final int MIN_TREEIFY_CAPACITY = 64;//树化时数组长度的阈值

4.hashmap Node属性

//hashmap中节点的基本属性,实现get,set方法。重写了hashCode、toString、equals方法。 属性在上文有介绍
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;
        }

        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;
        }
    }
    //扰动函数,用于计算hash值,在之后专门专题讲解。
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    //在发送hash冲突的时候。用于比较两个node。
    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;
    }
    
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

5.hashmap 构造器原理与字段

    //用于寻找大于或等于capacity的最小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;
    }
    
//					字段
transient Node<K,V>[] table; //hashMap数组的表示

transient Set<Map.Entry<K,V>> entrySet; //entry节点

transient int size; //数组长度

transient int modCount; //添加的元素个数

int threshold; //合理的初始化数组长度,根据tableSizeFor()得到,用于手动设置时使用

final float loadFactor; //负载因子,用于手动设置时使用

//					构造器
//构造器一:定义Node[]数组初始长度,与负载因子
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);
    }
    
//构造器二:定义Node[]数组初始长度,默认负载因子
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
//构造器三:仅创建HashMap对象,并初始化负债因子为0.75f
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
    
//构造器四:转化hashmap的父类
public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //这个方法为,将map中所有数据插入到hashmap中,此文不再描述
        putMapEntries(m, false);
    }

6.hashmap树节点(简要分析)

hashmap树节点比较复杂,之后做专门的分析

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // 父节点
        TreeNode<K,V> left;	//左节点
        TreeNode<K,V> right;//右节点
        TreeNode<K,V> prev;    // 记录上一个节点
        boolean red;//节点红黑判断
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

7.hashmap get方法

//调用的GET方法
public V get(Object key) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? null : e.value;
}

//实际执行的GET方法
final Node<K,V> getNode(int hash, Object key) {
	Node<K,V>[] tab; 
    Node<K,V> first, e; 
    int n; K k;
    // table不为空 && table长度大于0 && table索引位置(根据hash值计算出)节点不为空
    if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
        // first的key等于传入的key则返回first对象
        if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
            return first;
        //first的key不等于传入的key则说明是链表,向下遍历
        if ((e = first.next) != null) {
            // 判断是否为TreeNode,是则为红黑树
            // 如果是红黑树节点,则调用红黑树的查找目标节点方法getTreeNode
            if (first instanceof TreeNode)
                return ((TreeNode<K,V>)first).getTreeNode(hash, key);
            //走下列步骤表示是链表,循环至节点的key与传入的key值相等
            do {
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);
        }
    }
    //找不到符合的返回空
    return null;
}

7.hashmap put方法

//掉用的PUT方法,hash(key)调用本例中的hash()方法
public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
}


/**
 * 实际执行的PUT方法 
 * Implements Map.put and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to put
 * @param onlyIfAbsent if true, don't change existing value
 * @param evict if false, the table is in creation mode.
 * @return previous value, or null if none
 */ 
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
    Node<K,V>[] tab;
    Node<K,V> p;
    int n, i;
    
    // table是否为空或者length等于0, 如果是则调用resize方法进行初始化
    // table是一个 (Node<K,V>[] table;) Node类型的数组
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
        
    // 通过hash值计算索引位置, 如果table表该索引位置节点为空则新增一个
    if ((p = tab[i = (n - 1) & hash]) == null) // 将索引位置的头节点赋值给p
        tab[i] = newNode(hash, key, value, null);
    
    else { // table表该索引位置不为空
        Node<K,V> e; K k;
        //判断p节点的hash值和key值是否跟传入的hash值和key值相等
        if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
            e = p; // 如果相等, 则p节点即为要查找的目标节点,赋值给e
        // 判断p节点是否为TreeNode, 如果是则调用红黑树的putTreeVal方法查找目标节点
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        // 走到这代表p节点为普通链表节点
        else {
            // 遍历此链表, binCount用于统计节点数
            for (int binCount = 0; ; ++binCount) {
                //p.next为空代表目标节点不存在
                if ((e = p.next) == null) {
                    //新增一个节点插入链表尾部
                    p.next = newNode(hash, key, value, null);
                    //如果节点数目超过8个,调用treeifyBin方法将该链表转换为红黑树
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                //e节点的hash值和key值都与传入的相等, 则e即为目标节点,跳出循环
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        // e不为空则代表根据传入的hash值和key值查找到了节点,将该节点的value覆盖,返回oldValue
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e); // 用于LinkedHashMap
            return oldValue;
        }
    }
    //map修改次数加1
    ++modCount;
    
    //map节点数加1,如果超过阀值,则扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict); // 用于LinkedHashMap
    return null;
}

8.hashmap resize()方法

final Node<K,V>[] resize() {
        //oldTab保存未扩容的tab
        Node<K,V>[] oldTab = table;
        //oldTab最大容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //oldTab阀值
        int oldThr = threshold;
        int newCap, newThr = 0;
        //如果老map有值
        if (oldCap > 0) {
            // 老table的容量超过最大容量值,设置阈值为Integer.MAX_VALUE,返回老表
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            //老table的容量没有超过最大容量值,将新容量赋值为老容量*2,如果新容量<最大容量并且老容量>=16, 则将新阈值设置为原来的两倍
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }else if (oldThr > 0){ // 老表的容量为0, 老表的阈值大于0, 是因为初始容量被放入阈值
            newCap = oldThr;    // 则将新表的容量设置为老表的阈值
        //放第一个值时,对数组容量及阈值进行初始化。
        }else {   //老表的容量为0, 老表的阈值为0, 则为空表,设置默认容量和阈值
            newCap = DEFAULT_INITIAL_CAPACITY; //16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //12
        }
        // 如果新阈值为空, 则通过新的容量*负载因子获得新阈值
        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) { // 将索引值为j的老表头节点赋值给e
                    oldTab[j] = null; //将老表的节点设置为空, 以便垃圾收集器回收空间
                    // 如果e.next为空, 则代表老表的该位置只有1个节点,
                    // 通过hash值计算新表的索引位置, 直接将该节点放在该位置
                    if (e.next == null) //
                        newTab[e.hash & (newCap - 1)] = e;
                    //e.next不为空,判断是否是红黑树
                    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;
                            //如果e的hash值与老表的容量进行与运算为0,则扩容后的索引位置跟老表的索引位置一样
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            //如果e的hash值与老表的容量进行与运算为1,则扩容后的索引位置为:
                            //	老表的索引位置+oldCap
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null; // 最后一个节点的next设为空
                            newTab[j] = loHead; // 将原索引位置的节点设置为对应的头结点
                        }
                        if (hiTail != null) {
                            hiTail.next = null; // 最后一个节点的next设为空
                            newTab[j + oldCap] = hiHead; // 将索引位置为原索引+oldCap的节点设置为对应的头结点
                        }
                    }
                }
            }
        }
        return newTab;
    }

9.hashmap remove()方法

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

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;
    // 如果table不为空并且根据hash值计算出来的索引位置不为空, 将该位置的节点赋值给p
    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;
        // 如果p的hash值和key都与入参的相同, 则p即为目标节点, 赋值给node
        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)  // 如果p是TreeNode则调用红黑树的方法查找节点
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {    // 遍历链表查找符合条件的节点
                    // 当节点的hash值和key与传入的相同,则该节点即为目标节点
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;    // 赋值给node, 并跳出循环
                        break;
                    }
                    p = e;  // p节点赋值为本次结束的e
                } while ((e = e.next) != null); // 指向像一个节点
            }
        }
        // 如果node不为空(即根据传入key和hash值查找到目标节点),则进行移除操作
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) { 
            if (node instanceof TreeNode)   // 如果是TreeNode则调用红黑树的移除方法
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            // 走到这代表节点是普通链表节点
            // 如果node是该索引位置的头结点则直接将该索引位置的值赋值为node的next节点
            else if (node == p)
                tab[index] = node.next;
            // 否则将node的上一个节点的next属性设置为node的next节点, 
            // 即将node节点移除, 将node的上下节点进行关联(链表的移除)    
            else 
                p.next = node.next;
            ++modCount; // 修改次数+1
            --size; // table的总节点数-1
            afterNodeRemoval(node); // 供LinkedHashMap使用
            return node;    // 返回被移除的节点
        }
    }
    return null;
}

总结篇

  1. 在JDK8 HashMap使用的是懒加载模式,也就是说,在默认初始化hashmap的时候,并不会在内存中创建一个长度为16的数组。而是在第一次put数据的时候才会创建。
  2. 负载因子的作用:默认负载因子为0.75.也就是说,hashmap在put数据的时候,发现数组中75%的index中都有了数据,就会进行一次扩容。每一次扩容大小均为2^n。(默认情况下,首次初始化数组长度为16,那么扩容阈值就位12)
  3. 链表转化为红黑树的条件:1.单个index中的链表长度超过8。 2.当前散列表长度打到64。
  4. put算法:
    1、对比hash值。如果节点已经存在,则更新原值。
    2、如果节点不存在,则插入数组中,如果数组已经有值,则判断是否是红黑树,如果是,则调用红黑树方法插入
    3、如果插入的是链表,插入尾部,然后判断节点数是否超过8,如果超过,则转换为红黑树
    4、先插入的数据,后面判断是否超过阀值再进行的扩容
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值