Comparator 比较器

1.语法

   创建Comparator比较器的实现类,重写compare方法

import java.util.Comparator;

public class 实现类名 implements Comparator<被排序的类名> {
    /**
     * 存放比较规则
     * @param o1 the first object to be compared.
     * @param o2 the second object to be compared.
     * @return
     */
    @Override
    public int compare(被排序的类名 o1, 被排序的类名 o2) {
        return 0;
    }
}

2.排序规则

(1)从小到大

         o1的值大于o2的值,返回正数

         o1的值小于o2的值,返回负数

         o1的值等于o2的值,返回0 

(2)从大到小

         o1的值大于o2的值,返回负数

         o1的值小于o2的值,返回正数

         o1的值等于o2的值,返回0 

package com.by.static_;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        //从大到小
        if(o1.getScore()>o2.getScore()){
            return -1;
        } else if (o1.getScore() < o2.getScore()) {
            return 1;
        }
        return 0;
    }
}

3.在方法中传入比较实现类对象

package com.test;

import com.by.static_.Student;
import com.by.static_.StudentComparator;

import java.util.Arrays;

public class StudentTest {
    public static void main(String[] args) {
        Student student1 = new Student("张三",18,80.5);
        Student student2 = new Student( "李四",19,90.5 );
        Student student3 = new Student( "王五",20,100.5 );
        Student[] students= new Student[]{student1,student2,student3};
        Arrays.sort(students,new StudentComparator());
        for (Student student :students){
            System.out.println(student.getScore());
        }
    }
}

注:在Java中,Comparator是一个接口,它允许你定义一个比较逻辑,用于对对象进行排序或比较。Comparator接口通常与Collections.sort()Arrays.sort()方法一起使用,对集合或数组中的对象进行排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值