java Arrays.sort 自定义排序

package com.data.entity;

import java.util.Comparator;

public class StudentComparator implements Comparator {
    @Override
    public int compare(Student o1, Student o2) {
        /*
        * - 从小到大:
              - o1的值>o2的值,return正数
              - o1的值o2的值,return负数
              - o1的值 o2.getAge()) {
            return 1;
        } else if (o1.getAge() < o2.getAge()) {
            return -1;
        } else {  //年龄相同
            if(o1.getScore()>o2.getScore()){
                return -1;
            }else if(o1.getScore()
package com.data.entity;

public class Student {
    public String Name;
    public int Age;
    public double Score;

    public Student(){}
    public Student(String Name,int Age,double Score){
        this.Name=Name;
        this.Age=Age;
        this.Score=Score;
    }

    public String getName(){
        return this.Name;
    }

    public int getAge(){
        return this.Age;
    }

    public double getScore(){
        return this.Score;
    }






}
import com.data.entity.Student;
import com.data.entity.StudentComparator;

import java.util.Arrays;

// 按两次 Shift 打开“随处搜索”对话框并输入 `show whitespaces`,
// 然后按 Enter 键。现在,您可以在代码中看到空格字符。
public class Main {
    public static void main(String[] args) {
        //创建一个学生数组
        Student[] ss = {new Student("zhangsan", 21, 98.0),
                new Student("lisi", 20, 88.5),
                new Student("wangwu", 22, 67.0),
                new Student("wangwu2", 22, 77.0)};
        //根据学生年龄从小到大的排序
        Arrays.sort(ss,new StudentComparator());


        for (int i = 0; i < ss.length; i++) {
            System.out.println(ss[i].getName()+"  "+ss[i].getAge()+  "  "+ss[i].getScore());
        }
    }
}

你可能感兴趣的:(java,开发语言)