JDK源码==》TreeMap类学习

本文详细探讨了JDK中TreeMap类的put操作,从首次添加元素到非首次添加的流程,包括compare方法、root节点创建、插入后的调整如k.compareTo(t.key)、fixAfterInsertion及rotateLeft等。此外,还提到了containsKey、containsValue、get、replace和clear等关键方法的工作原理,揭示了TreeMap基于红黑树的内部数据结构及其影响。
摘要由CSDN通过智能技术生成


1、主要的成员变量及构造

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable {
   
    
    private final Comparator<? super K> comparator;

    private transient Entry<K,V> root;
    
    private transient int size = 0;
    
    private transient int modCount = 0;
    
   	private static final boolean RED   = false;
    private static final boolean BLACK = true;
    
    private transient EntrySet entrySet;
    private transient KeySet<K> navigableKeySet;
    private transient NavigableMap<K,V> descendingMap;
    
    private static final Object UNBOUNDED = new Object();
    
    public TreeMap() {
   
        comparator = null;
    }
	public TreeMap(Comparator<? super K> comparator) {
   
        this.comparator = comparator;
    }
    public TreeMap(Map<? extends K, ? extends V> m) {
   
        comparator = null;
        putAll(m);
    }
    public TreeMap(SortedMap<K, ? extends V> m) {
   
        comparator = m.comparator();
        try {
   
            buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
        } catch (java.io.IOException cannotHappen) {
   
        } catch (ClassNotFoundException cannotHappen) {
   
        }
    }
    ..............................
}    
2、put添加元素

先创建一个TreeMap实例

public class TreeMapDemo {
   

    public static void main(String[] args) {
   
        TreeMap<Object, Object> treeMap = new TreeMap<>();
        treeMap.put("aa","11");
        treeMap.put("bb","22");
        treeMap.put("cc","44");
        treeMap.put("dd","33");
        treeMap.put("ee","10");
    }
}
put添加元素执行的流程
	// 由于添加的键和值都是String类型的,且初始化创建实例指定的泛型类型都为Object,String也是Object的子类
	public V put(K key, V value) {
   
        // 默认初始的时候null
        Entry<K,V> t = root;
        // 判断根节点是否为null
        if (t == null) {
   
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
		......................
    }
第一次添加元素,需要执行的compare(key, key)方法
	final int compare(Object k1, Object k2) {
   
        return comparator==
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值