为什么要将TreeMap单独的拿出来写呢?必然有它的必要性。
在之前的Map共性方法的文章中,我们知道TreeMap底层用到的是二叉树的数据结构。既然是用到了二叉树,那它存入的元素必然有它特定的顺序,没错这个顺序是可以自己定义的。下面我们就来介绍TreeMap如何给存入元素排序。
之前我们研究过TreeSet给存入元素排序的方法,很巧TreeMap和TreeSet实现的方法相同,它也具有两种方式,一种是让元素实现Comparable接口覆盖CompareTo()方法,另一种是创建一个比较器实现Comparator接口覆盖compare()方法。和TreeSet实现的方式是一样的。
我们可通过示例来了解。
示例代码:
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
//用比较器实现排序,这里是按年龄排序
class StuNameComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName());
if (num == 0)//姓名相同判断年龄
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
return num;
}
}
// 学生类,这里实现了Comparable接口覆盖CompareTo()方法让其排序
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String toString() {
return "姓名:"+name + ",年龄:" + age;
}
// 这里是按年龄排序
@Override
public int compareTo(Student s) {
int num = new Integer(this.age).compareTo(new Integer(s.age));
if (num == 0)//年龄相同判断姓名
return this.name.compareTo(s.name);
return num;
}
}
public class MapDemo {
public static void main(String[] args) {
TreeMap<Student, String> tm = new TreeMap<Student, String>(
new StuNameComparator());//传入了比较器
tm.put(new Student("L01", 20), "北京");
tm.put(new Student("L02", 19), "长春");
tm.put(new Student("L03", 22), "长沙");
tm.put(new Student("L04", 21), "湘潭");
Set<Map.Entry<Student, String>> entryset = tm.entrySet();// 将映射关系存入Set
Iterator<Map.Entry<Student, String>> it = entryset.iterator();// 获取到迭代器
while (it.hasNext()) {
Map.Entry<Student, String> me = it.next();
Student stu = me.getKey();//获取学生信息
String addr = me.getValue();//获取住址
System.out.println(stu + ",住址:" + addr);
}
}
}
未传入比较器的输出结果:
当两种比较器都存在是还是以比较器的顺序为主。
我们可以看出和TreeSet的实现方式是一个样的。同样的只要是底层是二叉树的数据结构时它就具有特定顺序,就有比较存入元素的方法。