Java中比较器的使用

您所在的位置:网站首页 java中comparator的用法 Java中比较器的使用

Java中比较器的使用

2024-07-13 10:48:43| 来源: 网络整理| 查看: 265

很多情况下,我们需要对数据进行排序,但是java自带的比较器只能比较基本数据类型,比如我们自己定义一个Student类,如果用默认的Array.sort()方法进行排序,他会按照内存地址进行排序,那么这个排序毫无意义,此时我们就需要自己定义一个比较器,按照我们想要的比较方式来进行排序。 我们需要定义一个比较器,实现java.util.Comparator接口,会需要重写一个compare()方法,如下

public static class CustomeComparator implements Comparator{ // 根据学生成绩进行排序 @Override public int compare(Student st1, Student st2) { return st1.socre-st2.socre; } }

这就是一个基本的比较器,其返回值分三种

负数: 前者 < 后者 0: 两者相等 正数: 前者 > 后者 public static void main(String[] args) { Student student1 = new Student("A", 18, 76); Student student2 = new Student("B", 22, 85); Student student3 = new Student("C", 31, 64); Student[] students = new Student[] { student1, student2, student3 }; for (Student student : students) { System.out.println(student); } System.out.println("------ 排序后 --------"); Arrays.sort(students, new CustomeComparator()); for (Student student : students) { System.out.println(student); } }

使用的时候直接把需要排序的数组和自定义比较器丢进sort()即可,可以看看打印前后的顺序。对Array.sort()和Collections.sort()不太了解的朋友可以去自行百度,我这里不做过多解释。

Student [name=A, age=18, socre=76] Student [name=B, age=22, socre=85] Student [name=C, age=31, socre=64] ------ 排序后 -------- Student [name=C, age=31, socre=64] Student [name=A, age=18, socre=76] Student [name=B, age=22, socre=85]

一个简单的比较器就完成了,可以根据自己的需求进行定制。 后面贴出完整代码:

import java.util.Arrays; import java.util.Comparator; public class MyComparator { public static class Student{ public String name; public int age; public int socre; public Student(String name, int age, int socre) { super(); this.name = name; this.age = age; this.socre = socre; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", socre=" + socre + "]"; } } public static class CustomeComparator implements Comparator{ // 根据学生成绩进行排序 @Override public int compare(Student st1, Student st2) { return st1.socre-st2.socre; } } public static void main(String[] args) { Student student1 = new Student("A", 18, 76); Student student2 = new Student("B", 22, 85); Student student3 = new Student("C", 31, 64); Student[] students = new Student[] { student1, student2, student3 }; for (Student student : students) { System.out.println(student); } System.out.println("------ 排序后 --------"); Arrays.sort(students, new CustomeComparator()); for (Student student : students) { System.out.println(student); } } }


【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭