小言_互联网的博客

Java中 Collections.sort()方法

285人阅读  评论(0)

本着简单的原则,我们来实现用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别忘了写<Student>的泛型
所有代码

package cn.Try;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class Main{
    public static void main(String[] args){
        Student one=new Student(70,17);
        Student two=new Student(70,16);
        Student three=new Student(70,30);
        Student four=new Student(70,13);
        Student five=new Student(70,17);
        LinkedList<Student> myList=new LinkedList<Student>();
        myList.add(one);
        myList.add(two);
        myList.add(three);
        myList.add(four);
        myList.add(five);
        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;
            }
        });
        for(int i=0;i<myList.size();i++){
            System.out.println(myList.get(i).score+"  "+myList.get(i).age+"岁");
        }
    }
}
class Student{
    public int score;
    public int age;
    Student(int score,int age){
        this.age=age;
        this.score=score;
    }
}

转载:https://blog.csdn.net/Architect_chaser/article/details/102488450
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场