TreeMap
Source code analysis: https://blog.csdn.net/qq_23211905/article/details/76691961
The bottom layer of TreeMap is processed based on red-black trees. The time complexity of query, insertion and deletion is O(logN). Insertion and deletion will involve left-hand rotation, right-hand rotation and coloring of the red-black tree.
TreeMap is not a thread safe class.
TreeSet:
private transient NavigableMap<E,Object> m; TreeSet(NavigableMap<E,Object> m) { this.m = m; } public TreeSet() { this(new TreeMap<E,Object>()); }
A NavigableMap is maintained in the TreeSet source code. When an object is created directly, a TreeMap is created. Therefore, the underlying implementation principle of TreeSet is the same as that of TreeMap, which is implemented by red-black trees.
The relationship between TreeSet and TreeMap: Most of the methods in TreeSet are implemented by directly calling the TreeMap method.
The difference between the two: The
same points:
1: TreeMap and TreeSet are both asynchronous collections, so they cannot be shared between multiple threads, but the method Collections.synchroinzedMap() can be used to achieve synchronization.
2: The running speed is slower than that of Hash sets. The time complexity of their internal operations on elements is O(logN), while HashMap/HashSet is O(1).
3: Both TreeMap and TreeSet are ordered collections, which means that the values they store are in good order.
Differences:
1: The main difference is that TreeSet and TreeMap implement Set and Map interfaces respectively.
2: TreeSet stores only one object, while TreeMap stores two objects Key and Value (only key objects are ordered).
3: There cannot be duplicate objects in TreeSet, but can exist in TreeMap.
: