* 特点: 可以对元素进行排序 , 而排序分为两种方式
1. 自然排序
2. 比较器排序
那么我们到底使用的是自然排序还是比较器排序 , 取决于我们在创建TreeSet集合对象的时候所选定的构造方法
如果我们选择是无参的构造方法,那么我们使用的就是自然排序 , 如果我们选择的是接收一个Comparator参数的构造方法
那么我们使用的就是比较器排序
如果我们选择的是自然排序对元素有要求 , 要求元素必须去实现Comparable这个接口
TreeMap 保证元素唯一性依赖于compareTo 或者 compare方法的返回值是否为 0
import java.util.Comparator;
import java.util.TreeMap;
import com.heima.bean.Student;
public class Demo_TreeMap {
/**
*
* TreeMap集合键是Student值是String的案例
*/
public static void main(String[] args) {
//demo1();
TreeMap<Student, String> tm = new TreeMap<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getName().compareTo(s2.getName()); //按照姓名比较
return num == 0 ? s1.getAge() - s2.getAge() : num;
}
});
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("赵六", 43), "深圳");
tm.put(new Student("王五", 33), "广州");
System.out.println(tm);
}
public static void demo1() {
TreeMap<Student, String> tm = new TreeMap<>();
tm.put(new Student("张三", 23), "北京");
tm.put(new Student("李四", 13), "上海");
tm.put(new Student("王五", 33), "广州");
tm.put(new Student("赵六", 43), "深圳");
System.out.println(tm);
}
}