TreeMap
约 406 字大约 1 分钟
2024-08-08
HashMap 是一种以空间换时间的映射表,它的实现原理决定了内部的 Key 是无序的,即遍历 HashMap 的 Key 时,其顺序是不可预测的
还有一种 Map,它在内部会对 Key 进行排序,这种 Map 就是 SortedMap。注意到SortedMap是接口,它的实现类是 TreeMap
栗子
SortedMap 保证遍历时以 Key 的顺序来进行排序。例如,放入的 Key 是 "apple"、"pear"、"orange",遍历的顺序一定是 "apple"、"orange"、"pear",因为 String 默认按字母排序
public static void main(String[] args) {
Map<String, Integer> map = new TreeMap<>();
map.put("orange", 1);
map.put("apple", 2);
map.put("pear", 3);
for (String key : map.keySet()) {
System.out.println(key);
}
// apple orange pear
}如果作为 Key 的 class 没有实现 Comparable 接口,那么,必须在创建 TreeMap 时同时指定一个自定义排序算法
public static void main(String[] args) {
Map<Person, Integer> map = new TreeMap<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.name.compareTo(o2.name);
}
});
map.put(new Person("Tom"), 1);
map.put(new Person("Bob"), 2);
map.put(new Person("Lily"), 3);
for (Map.Entry<Person, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey().name);
}
// Bob Lily Tom
}public class Person {
public String name;
public Person(String name) {
this.name = name;
}
}Person 类并未覆写 equals() 和 hashCode(),因为 TreeMap 不使用 equals() 和 hashCode()
注意到 Comparator 接口要求实现一个比较方法,它负责比较传入的两个元素 a 和 b
如果
a < b,则返回负数,通常是-1如果
a == b,则返回0如果
a > b,则返回正数,通常是1。TreeMap内部根据比较结果对Key进行排序
如果自己手写 if 判断比较,记得要判断三种情况,否则 get() 有的数据为 null