本着简单的原则,我们来实现用Collection
的静态方法sort()的讲解,其中,只需要将实现Collection
的集合(LinkedList,ArrayList,HashSet,TreeSet
)等直接写入sort()
方法中就可以自动按照升序排序,那么如果想要降序怎么办,或者有是有是自定义的类型,想按照自己的想法排序怎么办?
代码如下
class Student{
public int score;
public int age;
Student(int score,int age){
this.age=age;
this.score=score;
}
}
这是我们定义的类,要使用sort()方法,本着简单的原则,我们使用匿名内部类来简化代码
Collections.sort(myList,new Comparator<Student>(){
public int compare(Student o1,Student o2){
int result=o1.score-o2.score;
if(result==0){
result=o2.age-o1.age;
}
return result;
}
});
这句代码直接实现排序,意思是,按照成绩升序排序,如果成绩相同,按照年龄降序排序。注意Comparator
别忘了写<