Java自定义排序

实现Comparator接口

实现该接口需要重写compare()方法

        Arrays.sort(students, new Comparator<Student>() {
            @Override
            // 升序  o1 - o2
            // 降序  o2 - o1
            public int compare(Student o1, Student o2) {
                if(o1.age == o2.age)
                    return o1.id - o2.id;
                return o2.age - o1.age;
            }
        });

实现Comparable接口

实现该接口需要重写compareTo()方法

		class Student implements Comparable<Student>{
		
		    int id;
		    int age;
		
		    public Student(int id,int age){
		        this.id = id;
		        this.age = age;
		    }
		
		
		    @Override
		    // 升序  this - o
		    // 降序  o - this
		    public int compareTo(Student o) {
		        if(this.age == o.age)
		            return o.id - this.id;
		        return this.age - o.age;
		    }
		}

完整代码

import java.util.Arrays;
import java.util.Comparator;

public class 自定义排序 {

    public static void main(String[] args){

        Student[] students = new Student[10];

        students[0] = new Student(1001,5);
        students[1] = new Student(1002,4);
        students[2] = new Student(1003,3);
        students[3] = new Student(1004,2);
        students[4] = new Student(1005,1);
        students[5] = new Student(1006,1);
        students[6] = new Student(1007,2);
        students[7] = new Student(1008,3);
        students[8] = new Student(1009,4);
        students[9] = new Student(1011,5);

        System.out.println("Comparator:根据年龄降序排序,如果年龄相同,则根据id升序");

        // 根据年龄降序排序,如果年龄相同,则根据id升序
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            // 升序  o1 - o2
            // 降序  o2 - o1
            public int compare(Student o1, Student o2) {
                if(o1.age == o2.age)
                    return o1.id - o2.id;
                return o2.age - o1.age;
            }
        });

        for(Student s : students)
            System.out.println(s.id + " " + s.age);

        System.out.println("Comparable:根据年龄升序排序,如果年龄相同,则根据id降序");

        // 根据年龄升序排序,如果年龄相同,则根据id降序
        Arrays.sort(students);
        for(Student s : students)
            System.out.println(s.id + " " + s.age);
    }

}


class Student implements Comparable<Student>{

    int id;
    int age;

    public Student(int id,int age){
        this.id = id;
        this.age = age;
    }


    @Override
    // 升序  this - o
    // 降序  o - this
    public int compareTo(Student o) {
        if(this.age == o.age)
            return o.id - this.id;
        return this.age - o.age;
    }
}

运行结果

Comparator:根据年龄降序排序,如果年龄相同,则根据id升序
1001 5
1011 5
1002 4
1009 4
1003 3
1008 3
1004 2
1007 2
1005 1
1006 1
Comparable:根据年龄升序排序,如果年龄相同,则根据id降序
1006 1
1005 1
1007 2
1004 2
1008 3
1003 3
1009 4
1002 4
1011 5
1001 5
posted @ 2022-11-07 19:07  老羊肖恩  阅读(88)  评论(0编辑  收藏  举报