SortedMap概述
A {@link Map} that further provides a total ordering on its keys. 提供了key的排序;
The map is ordered according to the {@linkplain Comparable natural ordering} of its keys, or by a {@link Comparator} typically provided at sorted map creation time.
根据 key的自然排序 或 创建SortedMap时提供的Comparator 进行排序;
This order is reflected when iterating over the sorted map's collection views (returned by the {@code entrySet}, {@code keySet} and {@code values} methods).
排序结果 可以根据 entrySet(), keySet(), values() 方法 迭代展示;
All keys inserted into a sorted map must implement the {@code Comparable} interface.
所有的key需要实现Comparable接口;
All general-purpose sorted map implementation classes should provide four "standard" constructors:
所有实现SortedMap的class 应该提供标准构造器:
A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys.
无参构造,key自然排序;
A constructor with a single argument of type {@code Comparator}, which creates an empty sorted map sorted according to the specified comparator.
Comparator参数,key根据指定Comparator排序;
A constructor with a single argument of type {@code Map}, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering.
Map参数,key自然排序;
A constructor with a single argument of type {@code SortedMap}, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map.
SortedMap参数,key排序规则和SortedMap参数排序规则一致;
实现类
TreeMap
概述
A Red-Black tree based {@link NavigableMap} implementation. 基于NavigableMap的红黑树实现;
The map is sorted according to the {@linkplain Comparable natural ordering} of its keys, or by a {@link Comparator} provided at map creation time, depending on which constructor is used.
key自然排序 或 创建Map的Comparator排序;
This implementation provides guaranteed log(n) time cost for the {@code containsKey}, {@code get}, {@code put} and {@code remove} operations.
containsKey(), get(), put(), remove() 复杂度 log(n) ;
Note that this implementation is not synchronized. TreeMap是非同步的;
If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
如果多个线程并发访问,需要外部支持同步;
If no such object exists, the map should be "wrapped" using the {@link Collections.synchronizedSortedMap Collections. synchronizedSortedMap} method.
可以使用Collections.synchronizedSortedMap(), Collections. synchronizedSortedMap() 获取同步TreeMap;