TreeMap
类不只实现了Map
接口,还实现了Map
接口的子接口java.util.SortedMap
。由TreeMap
类实现的Map
集合,不容许键对象为null
。java
一种平衡二叉树的实现。数据结构
因为TreeMap
须要排序,因此须要一个Comparator
为键值进行大小比较.固然也是用Comparator
定位的.code
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 comparable paths 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 { 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; }
从put方法可看出,若是构造TreeMap指定了Comparator,使用Comparator做为比较依据;不然利用key实现的Comparable接口做为比较大小依据。排序
前面提到,HashMap的key无需,可是添加查找删除操做的时间复杂度都接近于O(1),LinkedHashMap的添加删除查找的时间复杂度也接近于O(1),并且按key能够有两种有序(按插入,按访问),那为何还须要一种时间复杂度为O(logn)的按key有序的数据结构? TreeMap
默认是按键值的升序排序,也能够指定排序的比较器(比较可定制),当用Iterator
遍历TreeMap
时,获得的记录是排过序的。接口
TreeMap便可经过构造时指定comparator进行排序,也可按照key实现的comparable接口排序,那么都实现了,而且排序规则不一样,默认使用哪一种?默认优先使用构造时传入的Comparator,而后才会使用key实现的comparable接口。get
通常在须要按天然排序或者按指定方式排序输出使用TreeMap
;按输入顺序输出,则使用LinkedHashMap
it
Thanks for reading! want moreio