TreeMap and TreeSet (English Version)

在这里插入图片描述
what is TreeMap:
TreeMap extends AbstractMap and implement NavigableMap
treeMap is a k-v pair set with order, it’s based on red-black tree’s navigableMap to implement. we can custom of sort principle or just use the default with based on the key.

first, let’s recall what is red-black tree:

  1. node is either red or black
  2. root is black
  3. every leaf is black
  4. every red node’s child node must be all black(means for every path, no two adjacent red node)
  5. every path has the exactly same number of black nodes.
    in summary, red black tree is a balanced binary search tree with less balance than AVL tree(because in order to maintain a perfect balance tree like AVL, we have to cost lot when add and remove)

总结:
1、TreeMap是根据key进行排序的,它的排序和定位需要依赖比较器或覆写Comparable接口,也因此不需要key覆写hashCode方法和equals方法,就可以排除掉重复的key,而HashMap的key则需要通过覆写hashCode方法和equals方法来确保没有重复的key。

2、TreeMap的查询、插入、删除效率均没有HashMap高,一般只有要对key排序时才使用TreeMap。

3、TreeMap的key不能为null,而HashMap的key可以为null。

4、TreeMap不是同步的。如果多个线程同时访问一个映射,并且其中至少一个线程从结构上修改了该映射,则其必须 外部同步。

一句话来说 TreeMap是有序的HashMap, TreeSet是有序的HashSet. 他们排序的方法是利用红黑树,从而达到能够较快存和取。

TreeMap的构造方法:
TreeMap()
使用键的自然顺序构造一个新的、空的树映射。
TreeMap(Comparator<? super K> comparator)
构造一个新的、空的树映射,该映射根据给定比较器进行排序。
TreeMap(Map<? extends K,? extends V> m)
构造一个与给定映射具有相同映射关系的新的树映射,该映射根据其键的自然顺序 进行排序。
TreeMap(SortedMap<K,? extends V> m)
构造一个与指定有序映射具有相同映射关系和相同排序顺序的新的树映射。
Treemap的其他很多方法都和hashmap相同 放心的用即可

如何定义排序比较器?
方法1: implement Comparable interface, and override compareTo method
方法2:在创建新对象的时候直接利用构造方法指定一个比较器:TreeMap(Comparator<? super K> comparator)

TreeSet也是一样的

posted @ 2020-04-29 05:00  EvanMeetTheWorld  阅读(15)  评论(0)    收藏  举报