同时实现了自身实现Comparable和传递比较器排序的方式。
public class MyTest {
/**
*
* @param args
*/
public static void main(String[] args) {
Student s1=new Student("abc",77);
Student s2=new Student("bdc",65);
Student s3=new Student("abe",65);
Student s4=new Student("cac",90);
List<Student> list=new ArrayList<Student>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
for(Student s : list){ //存入集合的顺序
System.out.println(s.name+":"+s.score);
}
System.out.println("=============================");
Collections.sort(list); //使用对象自身的排序方式
for(Student s : list){
System.out.println(s.name+":"+s.score);
}
System.out.println("=============================");
Collections.sort(list, new MyComparator()); //按照比较器指定的方式排序
for(Student s : list){
System.out.println(s.name+":"+s.score);
}
}
}
class Student implements Comparable<Student>{
public String name;
public int score;
public Student(String name,int score){
this.name=name;
this.score=score;
}
@Override
public int compareTo(Student o) {
if(this.score==o.score) //分数相等就按照名字的自然顺序
return this.name.compareTo(o.name);
else
return this.score-o.score; //按照分数的自然顺序
}
}
class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
if(o1.score==o2.score) //如果分数相等就按照名字比较的反序
return -o1.name.compareTo(o2.name);
else
return o2.score-o1.score; //按照分数大小的反序比较
}
}
|