该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
TreeMap特点:
- 只针对键来说元素唯一,不能为null,可自定义排序。(set集合特点)
- 底层数据结构红黑树(是一种平衡的二叉树)。
- 线程不安全。
可以按着key来做排序
Key不能null,key不能重复,值可以有多个null
不是线程安全的
public static void main(String[] args) {
//创建一个Map集合
Map<String, String> map = new TreeMap<>();
//向集合总加元素
map.put("b","白胜");
map.put("a","林冲");
map.put("e","富安");
map.put("c","富安");
//6个
System.out.println(map);
}
Person实现了comparable接口,我们的treemap可以根据key来做排序
public static void main(String[] args) {
//创建一个Map集合
Map<Person, String> map = new TreeMap<>();
//向集合总加元素
map.put(new Person("白日鼠", 30),"白胜");
map.put(new Person("豹子头", 28),"林冲");
map.put(new Person("及时雨", 35),"宋江");
System.out.println(map);
}