java Arrays.sort 自定义排序

package com.data.entity;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        /*
        * - 从小到大:
              - o1的值>o2的值,return正数
              - o1的值<o2的值, return负数
              - 相等return0
            - 从大到小:
              - o1的值>o2的值,return负数
              - o1的值<o2的值, return正数
              - 相等return0
        * */
        //根据学生年龄从小到大,   如果年龄相同  成绩排序
        if (o1.getAge() > o2.getAge()) {
            return 1;
        } else if (o1.getAge() < o2.getAge()) {
            return -1;
        } else {  //年龄相同
            if(o1.getScore()>o2.getScore()){
                return -1;
            }else if(o1.getScore()<o2.getScore()){
                return 1;
            }else{ return 0;}
            //return 0;
        }
        //return 0;
    }
}
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());
        }
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值