一.TreeSet类解析:
1.TreeSet是依靠TreeMap实现的。
2.TreeSet中不能有重复的元素,而且是有序排列的。
3.自定义的类要想实现排序,实现Comparable接口,重写compareTo()方法。或者在构造方法中传入一个比较器,这个比较器实现Comparator接口,重写compare()方法。
4.Comparator是在集合外部实现排序的。(Comparable是在集合内部实现排序的,大家可以搜一下)
5.对于java中自定义的类,TreeSet可以直接进行储存,因为像String、Integer等等这些类都实现了Comparable接口。
6.对于自定义类,如果没有排序方法,那么TreeSet中只能存入一个该类的对象。
二.Comparable和Comparator的实现:
Comparable:
public class Student implements Comparable{
int score;
String name;
public Student(int score,String name){
this.score = score;
this.name = name;
}
// 返回负整数、零或正整数,根据此对象是小于、等于还是大于指定对象。
public int compareTo(Object o) {
Student s = (Student)o;
return this.score-s.score;//升序 要是降序的话就把两个变量倒过来写。
}
public String toString(){
return "姓名:"+this.name+" 成绩:"+this.score;
}
}
测试类:
打印:
Comparator:
public class Student{
int score;
String name;
public Student(int score,String name){
this.score = score;
this.name = name;
}
public String toString(){
return "姓名 :"+this.name+" 成绩 :"+this.score;
}
}
class ComparableStudent implements Comparator{
public int compare(Object o1, Object o2) {
Student s1 = (Student)o1;
Student s2 = (Student)o2;
return s1.score-s2.score;
}
}
测试类:
打印: