JDK源码 -- Map

版权声明:转载原创博客请附上原文链接 https://blog.csdn.net/weixin_43495590/article/details/89406688

一:概述

前面讲解了有关Set实现原理,其中Set具体实现子类TreeSet、HashSet、LinkedHashSet底层分别采用TreeMap、HashMap、LinkedHashMap。前面做了一点简单的学习,在这里就是针对Map方向的集合做比较深入的探究

二:结构

Map结构图片

三:TreeMap

  1. 数据存储Entry实现
  2. 一定规则顺序比较器运用
  3. 重点方法put()实现分析
3.1 Entry实现

Map中定义了内部接口Entry并且在AbstractMap抽象类中使用SimpleEntry实现,遗憾的是TreeMap形象理解为树,需要自己对Entry进行重新定义实现

熟悉树结构的一下就能看出这些属性记录数据,同一层级依靠left、right维系,上下级依靠parent维系,层级扩展形成的最后就是树结构。最后看到黑就想到红,BLACK、RED是TreeMap定义的两个常量,所以最后就是TreeMap采用红黑树结构实现

        K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

3.2 比较器排序与Put

  1. 针对元素是否实现Comparable接口或是传入Comparator比较器进行了检测
  2. 实现Comparable接口情况下对null值传入做空指针异常抛出处理
  3. 根据比较器确定节点从属父节点,根据左小右大原则衔接
	// comparator属性记录实例化对象传入比较器参数
	private final Comparator<? super K> comparator;
	
	// root记录根节点
	private transient Entry<K,V> root;
	
    public V put(K key, V value) {
        Entry<K,V> t = root;

		// 根节点为空表示第一次储存数据
        if (t == null) {

			// 使用三目运算将未传入Comparator比较器的容器对象内元素强转为Comparable实例
			// 第一个作用限制容器内元素必须实现Comparable接口亦或是传入Comparator比较器
			// 第二个作用就是防止实现Comparable元素传入null值
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        // 如果比较器comparator不为空即初始化传入了该比较器
        // 使用比较器确定新节点的父节点,并根据左小右大原则安排节点顺序
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
		
		// 如果未传入比较器则默认已经实现Comparable接口
		// 验证null值并且做与上述if操作相同动作
        else {
            if (key == null)
                throw new NullPointerException();
            @SuppressWarnings("unchecked")
                Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        // 初始化节点,并将节点按照上面比较加入树结构
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }
    final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable<? super K>)k1).compareTo((K)k2)
            : comparator.compare((K)k1, (K)k2);
    }

四:HashMap

  1. 重点属性分析
  2. 内部Node实现
  3. 数据结构转换
  4. 扩容分析
4.1 重点属性
    //默认初始化容量大小16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;   
    //容量最大值
    static final int MAXIMUM_CAPACITY = 1 << 30; 
    //默认填充因子0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //节点转红黑树数量最大值
    static final int TREEIFY_THRESHOLD = 8; 
    //红黑树转链表节点最小值
    static final int UNTREEIFY_THRESHOLD = 6;
    //哈希桶数组
    transient Node<k,v>[] table; 
    //存放元素个数
    transient int size;
    //每次更改结构或者是扩容后的计数器
    transient int modCount;  
    //节点数量临界值,等于容量最大值 * 填充因子
    int threshold;
    //填充因子
    final float loadFactor;
4.2 内部Node实现

内部Node节点实现可以看到一个单向链表实现

//Node是单向链表,它实现了Map.Entry接口
static class Node<k,v> implements Map.Entry<k,v> {
    final int hash;
    final K key;
    V value;
    Node<k,v> next;
    //构造函数Hash值 键 值 下一个节点
    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;
    }
    //判断两个node是否相等,若key和value都相等,返回true。可以与自身比较为true
    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;
    }
}
4.3 数据结构转换
  1. JDK1.8之前的版本HashMap采用哈希表+链表方式实现
  2. JDK1.8开始采用哈希表+链表+红黑树方式实现
  3. 链表与树结构都是解决哈希冲突,转换极限采用属性值TREEIFY_THRESHOLD 、UNTREEIFY_THRESHOLD
  4. 根据重要方法put()实现解析
    put方法流程图
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
		//步骤1:判断如果table数组未初始化,或者初始化容量为0进行扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
		//步骤2:判断(n - 1) & hash]新插入元素哈希桶位置是否已经有Node元素存在,不存在直接new新节点
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
		//桶中已经有元素存在
        else {
            Node<K,V> e; K k;
			//步骤3:比较桶中元素哈希值、key值与插入元素相等
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
				//将第一个元素赋值给e,用e记录
                e = p;
			//步骤4:判断该桶放置为红黑树节点
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
			//步骤5:为链表节点
            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;
                       
}
4.4 扩容分析
  1. 扩容默认大小是两倍,会调整对应的临界值
  2. 扩容阶段数据迁移因为遍历链表会产生线程安全问题
    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) 
            newCap = oldThr;
        // 初始值赋值
        else {               
            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;
    }
4.5 JDK1.7扩容 死循环分析
  1. 扩容后链表顺序倒序
  2. 扩容操作Node节点数组为实例对象属性数组
五:LinkedHashMap、EnumMap

关于LinkedHashMap只需要记住继承自HashMap,通过单向链表+数组+双向链表的数据结构维护插入顺序

EnumMap就是专门储存key值为枚举类的Map,类声明限制泛型K必须继承自Enum抽象枚举类,put()方法中的key要求必须是泛型K。所以就限制了key必须是枚举类

public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
    implements java.io.Serializable, Cloneable
{
    public V put(K key, V value) {
        typeCheck(key);

        int index = key.ordinal();
        Object oldValue = vals[index];
        vals[index] = maskNull(value);
        if (oldValue == null)
            size++;
        return unmaskNull(oldValue);
    }

猜你喜欢

转载自blog.csdn.net/weixin_43495590/article/details/89406688
今日推荐