重新认识TreeMap
特点 TreeMap 类不仅实现了 Map 接口,还实现了 Map 接口的子接口 java.util.SortedMap 。由 TreeMap 类实现的 Map 集合,不允许键对象为 null 。 核心 红黑树 比较器实现大小比较。 红黑树 一种平衡二叉树的实现。 比较器 由于 TreeMap 需要排序,所以需要一个 Comparator 为键值进行大小比较.当然也是用 Comparator 定位的. Comparator 可以在创建 TreeMap 时指定 如果创建时没有确定,那么就会使用 key.compareTo() 方法,这就要求 key 必须实现 Comparable 接口. TreeMap 是使用Tree数据结构实现的,所以使用 compare 接口就可以完成定位了. put方法 public V put(K key, V value) { Entry<K,V> t = root; if (t == 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