一、Comparable 接口
当一个自定义的类,比如 Student 需要存储在 TreeSet 集合当中,可以为 Student 实现 Comparable 接口。因为 TreeSet 集合内部的元素是自然排序,而系统根本不知道自定义的类如何排序,所以需要我们人为地定义排序方法,也就是对 Comparable 接口中的 compareTo 方法进行重写。
public class Student implements Comparable<Student>{
String name;
int num;
//构造方法
public Student(String name,int num)
{
this.name=name;
this.num=num;
}
//get方法
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
//重写Comparable接口中的compareTo方法
@override
public int compareTo(Student o)
{
int a=0;
//比较num
if(this.getNum()<o.getNum()){a=-1;}
else if(this.getNum()>o.getNum()){a=1;}
//num相同的时候,比较name
else {a=this.getName().compareTo(o.getName());}
return a;
}
}
public static void main(String[] args)
{
Student st1=new Student("aaa",11);
Student st2=new Student("bbb",22);
Student st3=new Student("ccc",22);
TreeSet<Student> ts=new TreeSet();
ts.add(st1);
ts.add(st2);
ts.add(st3);
for(Student x:ts){System.out.println(x.getName());}
}
二、Comparator 比较器
上述情况中,如果 Student 不允许实现 Comparable 接口,可以另外定义一个 Comparator 比较器。如果既允许实现接口,又允许定义比较器,那么比较器的优先级大于接口。
public class Student implements Comparable<Student>{
String name;
int num;
//构造方法
public Student(String name,int num)
{
this.name=name;
this.num=num;
}
//get方法
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
}
public class StudentCompare implements Comparator<Student>{
public int compare(Student o1,Student o2)
{
int a=0;
//比较num
if(this.getNum()<o.getNum()){a=-1;}
else if(this.getNum()>o.getNum()){a=1;}
//num相同的时候,比较name
else {a=this.getName().compareTo(o.getName());}
return a;
}
}
Comparator 比较器实际上也是一个类,比如案例中的 StudentCompare 类,它要实现 Comparator 接口才能重写 Compare 方法。