我们知道,HashMap 放入的 Entry 是没有顺序的,而 LinkedHashMap 是根据 put 的顺序或者是访问的顺序来排序,而不是根据 key 的大小来排序。
那么 TreeMap 就有这样一个作用:根据 key 的大小进行排序。默认是升序的。
TreeMap 源码注释的第一句就说了:
A Red-Black tree based {@link NavigableMap} implementation.
所以首先要对红黑树有所了解。参考 wiki:红黑树,是一种自平衡二叉查找树。那么对于二叉查找树,参考 wiki:二叉搜索树 ,是指一棵树:
- 任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 任意节点的左、右子树也分别为二叉查找树;
- 没有键值相等的节点。
这样子的一棵树就成为二叉搜索树,那么这个树是会倾斜的,一倾斜就会导致效率的下降,所以说就有了一个平衡的概念,使其不会倾斜。
红黑树就采用了一些算法,使得能够保存平衡,具体的红黑树的概念实现个人觉得有点复杂,也先不了解了,这里主要是看看 TreeMap 是如何使用的。具体原理可以参考: Java提高篇(二七)-----TreeMap
TreeMap 的使用
根据源码的注释:
* 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.
那么,要么是我们放入的 Entry 实现了 Comparable 接口,要么是我们在创建 TreeMap 的时候提供一个 Comparator。
方式一:Entry 实现了 Comparable
如下代码:
public class Test {
public static void main(String args[]){
Map<Student,String> map = new TreeMap<>();
Student student1 = new Student(3);
Student student2 = new Student(1);
Student student3 = new Student(2);
Student student4 = new Student(0);
Student student5 = new Student(5);
map.put(student1,"a");
map.put(student2,"b");
map.put(student3,"c");
map.put(student4,"d");
map.put(student5,"e");
Iterator<HashMap.Entry<Student,String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
System.out.println(iterator.next().getKey().getStudentNum());
}
}
static class Student implements Comparable<Student>{
private int studentNum;
public Student(int studentNum){
this.studentNum = studentNum;
}
public int getStudentNum(){
return this.studentNum;
}
@Override
public int compareTo(Student o) {
if(o == null){
return 1;
}
if(o == this){
return 0;
}
if(this.studentNum == o.getStudentNum()){
return 0;
} else {
return studentNum > o.getStudentNum() ? 1 : -1;
}
}
}
}
输出如下:
0
1
2
3
5
方式二:提供 Comparator
public class Test {
public static void main(String args[]){
Comparator<Student> comparator = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.studentNum == o2.getStudentNum()){
return 0;
} else {
return o1.getStudentNum() > o2.getStudentNum() ? 1 : -1;
}
}
};
Map<Student,String> map = new TreeMap<>(comparator);
Student student1 = new Student(3);
Student student2 = new Student(1);
Student student3 = new Student(2);
Student student4 = new Student(0);
Student student5 = new Student(5);
map.put(student1,"a");
map.put(student2,"b");
map.put(student3,"c");
map.put(student4,"d");
map.put(student5,"e");
Iterator<HashMap.Entry<Student,String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){
System.out.println(iterator.next().getKey().getStudentNum());
}
}
static class Student{
private int studentNum;
public Student(int studentNum){
this.studentNum = studentNum;
}
public int getStudentNum(){
return this.studentNum;
}
}
}
可以获得同样输出。
(完)。