TreeMap的存储原理就是红黑树
    public V put(K key, V value) {
    Entry t = root; //root为根节点
    if (t == null) { //如果t为null,说明这是第一次put
    compare(key, key); // type (and possibly null) check,检查key是否为空
    root = new Entry<>(key, value, null); //将值赋给根节点
    size = 1;
    modCount++;
    return null;
    }
    int cmp; //比较结果
    Entry parent; //父节点
    // split comparator and comparable paths
    Comparator<? super K> cpr = comparator; //比较器
    if (cpr != null) {
    do { //通过do-while循环,一层一层往下找,遵循红黑树原理,小左大右,确认插入值的位置
    parent = t;
    cmp = cpr.compare(key, t.key);
    if (cmp < 0)
    t = t.left; //如果插入key小于当前节点t的key,将t的左侧节点赋给t,如果t不为null,进行下一轮比较
    else if (cmp > 0)
    t = t.right;//如果插入key大于当前节点t的key,将t的右侧节点赋给t,如果t不为null,进行下一轮比较
    else
    return t.setValue(value);//相等则直接赋值,进行覆盖操作
    } while (t != null);
    }
    else {
    if (key == null)
    throw new NullPointerException();
    @SuppressWarnings(“unchecked”)
    //如果比较器为null,手动创建一个比较器
    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 e = new Entry<>(key, value, parent);//将插入值封装成一个Entry对象
    //此时parent为最后一次比较的t对象,根据cmp的值决定插入值的位置
    if (cmp < 0)
    parent.left = e;
    else
    parent.right = e;
    //变色换位,保持树的相对平衡
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
    }

    private void fixAfterInsertion(Entry x) {
    x.color = RED; //首先将当前插入节点设为红色

    1. while (x != null && x != root && x.parent.color == _RED_) {<br /> if (_parentOf_(x) == _leftOf_(_parentOf_(_parentOf_(x)))) { //如果当前节点的父节点在祖父节点的左侧<br /> Entry<K,V> y = _rightOf_(_parentOf_(_parentOf_(x))); //获取当前节点祖父节点右侧节点,即父节点的兄弟<br /> if (_colorOf_(y) == _RED_) { //如果父节点兄弟节点为红色,则直接进行变色操作<br /> _setColor_(_parentOf_(x), _BLACK_);<br /> _setColor_(y, _BLACK_);<br /> _setColor_(_parentOf_(_parentOf_(x)), _RED_);<br /> x = _parentOf_(_parentOf_(x)); //将祖父节点设置为当前插入节点,继续进行循环平衡<br /> } else {<br /> if (x == _rightOf_(_parentOf_(x))) { //如果当前节点在父节点的右侧<br /> x = _parentOf_(x);<br /> rotateLeft(x); //先左旋<br /> }<br /> _setColor_(_parentOf_(x), _BLACK_);<br /> _setColor_(_parentOf_(_parentOf_(x)), _RED_);<br /> rotateRight(_parentOf_(_parentOf_(x))); //再右旋<br /> }<br /> } else { //同理<br /> Entry<K,V> y = _leftOf_(_parentOf_(_parentOf_(x)));<br /> if (_colorOf_(y) == _RED_) {<br /> _setColor_(_parentOf_(x), _BLACK_);<br /> _setColor_(y, _BLACK_);<br /> _setColor_(_parentOf_(_parentOf_(x)), _RED_);<br /> x = _parentOf_(_parentOf_(x));<br /> } else {<br /> if (x == _leftOf_(_parentOf_(x))) {<br /> x = _parentOf_(x);<br /> rotateRight(x);<br /> }<br /> _setColor_(_parentOf_(x), _BLACK_);<br /> _setColor_(_parentOf_(_parentOf_(x)), _RED_);<br /> rotateLeft(_parentOf_(_parentOf_(x)));<br /> }<br /> }<br /> }<br /> //保证根节点为黑色<br /> root.color = _BLACK_;<br />}