首页 > 技术文章 > 3.集合-Map接口

chuanqi1995 2022-03-04 14:32 原文

资料:https://gitee.com/chuanqi1995/java

Map集合的特点

  1. 能够存储唯一的列的数据(唯一,不可重复) Set
  2. 能够存储可以重复的数据(可重复) List
  3. 值的顺序取决于键的顺序
  4. 键和值都是可以存储null元素的

TreeMap

特点

TreeMap底层就是红黑树,所以他符合红黑树所有的特点

源码分析

初始化

private final Comparator<? super K> comparator; //比较器

private transient Entry<K,V> root; //根节点

/**
 * The number of entries in the tree
 */
private transient int size = 0; //大小

/**
 * The number of structural modifications to the tree.
 */
private transient int modCount = 0; //防止并发状态下数据结构发生变化的校验

Entry

K key; //键
V value; //值
Entry<K,V> left; //左子节点
Entry<K,V> right; //右子节点
Entry<K,V> parent; //父节点
boolean color = BLACK; //默认黑色

无参构造

/**
 * Constructs a new, empty tree map, using the natural ordering of its
 * keys.  All keys inserted into the map must implement the {@link
 * Comparable} interface.  Furthermore, all such keys must be
 * <em>mutually comparable</em>: {@code k1.compareTo(k2)} must not throw
 * a {@code ClassCastException} for any keys {@code k1} and
 * {@code k2} in the map.  If the user attempts to put a key into the
 * map that violates this constraint (for example, the user attempts to
 * put a string key into a map whose keys are integers), the
 * {@code put(Object key, Object value)} call will throw a
 * {@code ClassCastException}.
 */
public TreeMap() {
    comparator = null;
}

put()

/**
 * Associates the specified value with the specified key in this map.
 * If the map previously contained a mapping for the key, the old
 * value is replaced.
 *
 * @param key key with which the specified value is to be associated
 * @param value value to be associated with the specified key
 *
 * @return the previous value associated with {@code key}, or
 *         {@code null} if there was no mapping for {@code key}.
 *         (A {@code null} return can also indicate that the map
 *         previously associated {@code null} with {@code key}.)
 * @throws ClassCastException if the specified key cannot be compared
 *         with the keys currently in the map
 * @throws NullPointerException if the specified key is null
 *         and this map uses natural ordering, or its comparator
 *         does not permit null keys
 */
public V put(K key, V value) {
  	//root = null;
  	//t = null;
    Entry<K,V> t = root;
  	//第一次put会进入此判断
    if (t == null) {
      	//校验key是否为null
        compare(key, key); // type (and possibly null) check
				//创建一个Entry以传入的key value作为根节点
        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
  
  	//当第二次的时候 t != null进入以下逻辑
 		//t = <"a", 10>
    int cmp;
  	//定义一个父节点的对象
    Entry<K,V> parent;
    // split comparator and comparable paths
  	//初始化的时候comparator = nu l l
    Comparator<? super K> cpr = 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);
    }
    else {
      	//如果key == null就会抛异常
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        do {
          	//第一次循环的时候,把根节点当作父节点
          	//第二次循环的时候,根据下面的t去做决定
         		//parent = <"a", 10>
            parent = t;
          	//比较传入的key和父节点的key做比较
            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,以传入的 key value作为键值对,parent为父类
    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;
}
/** From CLR */
private void fixAfterInsertion(Entry<K,V> x) {
  	//插入的元素 默认为红色
    x.color = RED;
		//插入的元素不等于null
  	//插入的元素不等于根节点
  	//插入的节点的父类的颜色等于红色
    while (x != null && x != root && x.parent.color == RED) {
      	//父类节点在祖父节点的左节点
        if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
          	//获取叔叔节点
            Entry<K,V> y = rightOf(parentOf(parentOf(x)));
          	//叔叔节点是红色
            if (colorOf(y) == RED) {
              	//父节点设置为黑色
                setColor(parentOf(x), BLACK);
             		//叔叔节点设置为黑色
                setColor(y, BLACK);
              	//祖父节点设置为红色
                setColor(parentOf(parentOf(x)), RED);
              	//把祖父节点设置为当前节点
                x = parentOf(parentOf(x));
            } else { //叔叔节点是黑色
              	//当前节点是父节点的右节点
                if (x == rightOf(parentOf(x))) {
                  	//把父节点设置为当前节点
                    x = parentOf(x);
                  	//父节点进行左旋
                    rotateLeft(x);
                }
              	//父节点设置为黑色
                setColor(parentOf(x), BLACK);
              	//祖父节点设置为红色
                setColor(parentOf(parentOf(x)), RED);
              	//祖父节点右旋
                rotateRight(parentOf(parentOf(x)));
            }
        } else { //父类节点在祖父节点的右节点
          	//获取叔叔节点
            Entry<K,V> y = leftOf(parentOf(parentOf(x)));
          	//叔叔节点是红色
            if (colorOf(y) == RED) {
              	//父节点设置为黑色
                setColor(parentOf(x), BLACK);
              	//叔叔节点设置为黑色
                setColor(y, BLACK);
              	//祖父节点设置为红色
                setColor(parentOf(parentOf(x)), RED);
              	//祖父节点设置为当前节点
                x = parentOf(parentOf(x));
            } else { //叔叔节点是黑色
              	//当前节点是父节点的左节点
                if (x == leftOf(parentOf(x))) {
                  	//把父节点设置为当前节点
                    x = parentOf(x);
                  	//父节点进行右旋
                    rotateRight(x);
                }
              	//父节点设置为黑色
                setColor(parentOf(x), BLACK);
              	//祖父节点设置为红色
                setColor(parentOf(parentOf(x)), RED);
              	//祖父节点进行左旋
                rotateLeft(parentOf(parentOf(x)));
            }
        }
    }
  	//根节点设置为黑色
    root.color = BLACK;
}

左旋

/** From CLR */
private void rotateLeft(Entry<K,V> p) {
    if (p != null) {
        Entry<K,V> r = p.right;
        p.right = r.left;
        if (r.left != null)
            r.left.parent = p;
        r.parent = p.parent;
        if (p.parent == null)
            root = r;
        else if (p.parent.left == p)
            p.parent.left = r;
        else
            p.parent.right = r;
        r.left = p;
        p.parent = r;
    }
}

右旋

/** From CLR */
private void rotateRight(Entry<K,V> p) {
    if (p != null) {
        Entry<K,V> l = p.left;
        p.left = l.right;
        if (l.right != null) l.right.parent = p;
        l.parent = p.parent;
        if (p.parent == null)
            root = l;
        else if (p.parent.right == p)
            p.parent.right = l;
        else p.parent.left = l;
        l.right = p;
        p.parent = l;
    }
}

HashMap

JDK1.7及以前,底层实现是数组 + 链表

JDK1.8之后,底层是数组 + 链表 / 数组 + 红黑树

初始化

// 数组的默认长度为16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 数组的最大容量为10亿多
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认的扩容平衡因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转红黑树的临界值,当链表长度大于等于8的时候转换成红黑树
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转链表的临界值,当红黑树的节点小于等于6时转换成链表
static final int UNTREEIFY_THRESHOLD = 6;
// 链表转红黑树的另一个条件是,数组的长度要大于64
static final int MIN_TREEIFY_CAPACITY = 64;
// 数组结构
transient Node<K,V>[] table;
// Map集合中的元素个数
transient int size;
// 修改的次数
transient int modCount;
// 扩容的临界值
int threshold;
// 实际扩容因子
final float loadFactor;

put()

public V put(K key, V value) {
  	//hash(key) 以key为参数获取hash值
    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;
  	// 第一次table = null
 		// tab:数组结构 tab = null
    if ((tab = table) == null || (n = tab.length) == 0)
      	// n:数组长度,n = 16
      	// 第一次进来的时候resize()代表初始数组
        n = (tab = resize()).length;
  	// 根据hash值找到的数组的下标里面没有值得话,就直接赋值
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
      	// 根据hash值找到的数组下标里面有值的话,走下面的步骤
        Node<K,V> e; K k;
      	// 根据hash值找到的hash值与传的key转换的hash值相当的话 或者 根据hash值找到的key等于传入的key 就直接覆盖
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode) //根据hash值找到的数组位置是红黑树的话,就直接插入
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
          	// 表示节点是普通的链表
          	// 循环链表
            for (int binCount = 0; ; ++binCount) {
              	// 直至循环到尾节点指向的next是null
                if ((e = p.next) == null) {
                  	// 就把当前的值插入到链表的最底部
                    p.next = newNode(hash, key, value, null);
                  	// 当链表的长度大于等于7的时候,进行转换红黑树的判断
                    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;
}
final Node<K,V>[] resize() {
  	// table = null
  	// oldTab = null
    Node<K,V>[] oldTab = table;
  	// oldCap = 0
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
  	// oldThr = 0
    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 = 16
        newCap = DEFAULT_INITIAL_CAPACITY;
      	// newThr = 12
        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 = 12
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
  	// 创建了一个容量为16的数组
    Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  	// 当前数组结构就是一个容量为16的数组
  	//table = [16]{}
    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;
  	// 如果tab = null 或者
  	// 数组结构的长度赋值为n,n < 64的话继续扩容
    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);
    }
}

动态扩容resize()

final Node<K,V>[] resize() {
  	// oldTab = table = {e,e,e,e,e,e,e,e,e,e,e,null,null,null,null,null} length = 16
    Node<K,V>[] oldTab = table;
  	// oldCap = 16
    int oldCap = (oldTab == null) ? 0 : oldTab.length;
  	// oldThr = 12
    int oldThr = threshold;
    int newCap, newThr = 0;
    if (oldCap > 0) {
        if (oldCap >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return oldTab;
        }
      	// newCap = oldCap = 32
        else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                 oldCap >= DEFAULT_INITIAL_CAPACITY)
          	// newThr = 24
            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 = 24
    threshold = newThr;
    @SuppressWarnings({"rawtypes","unchecked"})
  	// 创建一个数组的长度为32
    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;
}

推荐阅读