Log[集合类-HashMap(含部分源码分析)]_20.03.25

参考博客:https://blog.csdn.net/carson_ho/article/details/79373134(真的谢谢这位博主!!)
https://blog.csdn.net/xingfei_work/article/details/79637878
一、简介
HashMap是Map接口的实现类,以键值对的形式存储数据,key.value均可以为null.
二、基本数据结构
2.1 HashMap1.7
HashMap1.7的数据结构为数组+链表形式,产生哈希冲突的结点都以头插法的形式插入bucket中。
存在问题是:1.当HashMap扩容后进行重新存储时会产生链表逆序的结果。
2.在多线程的情况下可能会产生环形链表死循环问题(两个线程同时扩容)
2.2 HashMap1.8
HashMap1.8的数据结构为数组+链表+红黑树(内容见红黑树篇(找不到就是还没写…)),插入形式是尾插法,当链表长度超过阈值8时(为什么是8见本篇Tips3),链表会变为红黑树,当元素小于6时会重新变为链表。
较1.7的优化:解决了链表逆序以及死循环的问题。
三、源码详解(基于1.8)
接口实现与类继承:
在这里插入图片描述
基本属性:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // 默认初始化容量16

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;//链表化阈值

static final int MIN_TREEIFY_CAPACITY = 64;//最小树化容量:map的容量在64之前需要树化时,首先考虑扩容,因为树化比较麻烦



/* ---------------- Static utilities -------------- */
//对key调用hashCode()再进行扰动处理得到hash值)
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}


transient Node<K,V>[] table;//实际存储键值对的数组

transient Set<Map.Entry<K,V>> entrySet;
transient int size;//当前数组元素个数
transient int modCount;//记录操作数
int threshold;//扩容阈值
final float loadFactor;//负载因子

链表结点Node:

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

//这是计算结点的hash值,跟插入时候计算的hash区分开来
    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) {//考察this和o的key和value是不是相等
        if (o == this)//引用的地址相等 那么这两组键值对绝对一毛一样 直接return true
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&//两个key的地址相等且值相等
                Objects.equals(value, e.getValue()))//两个value的地址相等且值相等
                return true;
        }
        return false;
    }
}

红黑树结点:

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);  
    }  
  
    // 返回当前节点的根节点  
    final TreeNode<K,V> root() {  
        for (TreeNode<K,V> r = this, p;;) {  
            if ((p = r.parent) == null)  
                return r;  
            r = p;  
        }  
    } 

构造方法:

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);//
}
//|= 按位或
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;
}


public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

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

3.1 插入
3.1.2 插入&扩容
先根据key值进行hash值的计算,然后进行扰动处理(与1.7相比少了几次扰动处理(扰动处理:位运算或者异或运算))

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
//计算出key的哈希值
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
     //对比hashtable,hashtable直接对key进行hashcode(),若key为null,抛异常
}
//正式开始插入流程
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab;//指向table数组的引用
     Node<K,V> p; //指向当前要插入的数组元素的位置,也就是table[i]
    int n, i;//n为数组长度 i为数组下标
    //如果table为空或者table长度为0,表示首次插入,就要对其进行扩容
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
     //i=(n-1)&hash是确定元素下标 p引用指向table[i] 如果table[i]是空,把新结点插入table[i]  
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {//如果table[i]并不为空,就要开始进行key的比较啦
        Node<K,V> e; K k;
        //k是数组中结点的key,key是要插入元素的key,k与key值相等&&两结点hash值也相等 就能证明是同一个结点
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;//e指向table[i]
            //判断table[i]是链表还是红黑树
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {//是链表,for循环遍历链表,在循环里面只处理了没有相同key而增长链表的情况
            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 &&//找到相同key的情况在后面处理
                    ((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;
}

接下来对resize()进行分析,有两种情况,一种是扩容,一种是初始化

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; // 没有超过的话则扩容有效,阈值也随之调大
    }
    else if (oldThr > 0) //表明用的是指定了初始化值或扩容因子的构造方法
        newCap = oldThr;
    else {               // zero initial threshold signifies using defaults
        newCap = DEFAULT_INITIAL_CAPACITY;
        newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
    }
    if (newThr == 0) {//如果阈值是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;//table指向新空间
    if (oldTab != null) {//旧空间内不为null,把旧值搬移到新空间
        for (int j = 0; j < oldCap; ++j) {
            Node<K,V> e;
            if ((e = oldTab[j]) != null) {
                oldTab[j] = null;//旧址置null方便gc
                if (e.next == null)//如果e是单独的元素,也就是不是链表,重新计算元素e在新数组的下标并把e放进去
                    newTab[e.hash & (newCap - 1)] = e;
                else if (e instanceof TreeNode)//如果e所在的数组元素是一颗红黑树
                    ((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;
                         //下标计算方法是hash()&length-1
                    //二进制表示中数组扩容后,length-1会刷新一个0为1(因为扩容是扩二倍)
                    //在进行与运算的时候,根据哈希值的不同,与刷新的那个1相与的值也不同
                    //所以在下面的判断中
                    //如果(e.hash & oldCap) == 0,则表明与刷新的1相与的是0,则结果与未扩容前没变化,所以存放的索引是原索引
                    //else,则表明与1相与的是1,则结果为未扩容前的二倍,所以存放的索引是原索引+旧容量
                        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;
}

辅助理解:
在这里插入图片描述
图片来源:https://blog.csdn.net/carson_ho/article/details/79373134
3.2 获取数据
哈希引用相等&&(key引用相等||key值相等)

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

/**
 * Implements Map.get and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @return the node, or null if none
 */
final Node<K,V> getNode(int hash, Object key) {//因为要进行key值是否相等的比对,所以不仅要传入能计算位置的hash值,也要传入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) {//数组不为空,长度大于0,table[i]不为空  是查找的前提
        if (first.hash == hash && //第一个结点的hash和要查的元素hash相等
            ((k = first.key) == key || (key != null && key.equals(k))))//与数组中的key值做对比
            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;
}

3.3 删除数据

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;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {//数组不为空,数组长度大于0,table[i]不为空
        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;//是的话node引用指向它
        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;
}

3.4 整个数组置空

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

Tips:1.键为null时,会在table[0]中查找key为null的元素,找到的话刷新value值,没找到的话将其插入
2.HshMap还实现了Cloneable接口(浅拷贝)和Serializable接口(序列化)。
3.树表转化的阈值为什么是8?
红黑树的平均查找长度是logn,log8=3;链表平均查找长度是n/2,8/2=4;这时才有必要进行转化。在树化过程中,先将节点包装成TreeNode,此时还是一条链表连接着数个TreeNode,然后再调用其他方法将链表变成红黑树
4.HashSet几乎全部方法都是依赖HashMap,属性是一个Map和一个Object对象(为了填充Value)
5.如何解决Hash冲突?三个方面:哈希算法、扩容机制、数据结构
6.为什么Integer,String更适合做key键?因为其类不可更改的原则,使得哈希值不可更改

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值