Java-----Comparable接口和Comparator接口

在Java中,我们会经常使用到自定义类,那我们如何进行自定义类的比较呢?

1.Comparable接口

普通数据的比较

        int a=10;int b=91;System.out.println(a<b);

那自定义类型可不可以这样比较呢?看一下代码

6bdf30df004947c5a3408055fb640003.png

我们发现会报错,因为自定义类型,stu1和stu2里面存的是引用,是无法直接根据姓名或年龄进行比较的。

1.1Comparable接口的使用

 如果想要自定义类型根据年龄和名字进行比较,这时候就要用到我们的Comparable接口。

54111f81c7bf4d569009d9641ad604d4.png

当我们观察Comparable接口的底层细节会发现有一个<T>和一个方法,<T>代表我们要比较的类型,方法是我们根据实际情况来重写compareTo方法,也就是比较的规则。

1.根据年龄比较 

自定义类中具体实现

class Student implements Comparable<Student>{public String name;public int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic int compareTo(Student o) {//根据年龄比较/*if(this.age>o.age){return 1;}else if (this.age==o.age){return 0;}else {return -1;}*/return this.age-o.age;}
}

完整代码

class Student implements Comparable<Student>{public String name;public int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic int compareTo(Student o) {//根据年龄比较/*if(this.age>o.age){return 1;}else if (this.age==o.age){return 0;}else {return -1;}*/return this.age-o.age;}
}
public class Test {public static void main(String[] args) {Student stu1=new Student("zhansan",18);Student stu2=new Student("man",24);System.out.println(stu1.compareTo(stu2));}
}

2.根据名字比较

class Student implements Comparable<Student>{public String name;public int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic int compareTo(Student o) {return this.name.compareTo(o.name);}
}
public class Test {public static void main(String[] args) {Student stu1=new Student("zhansan",18);Student stu2=new Student("man",24);System.out.println(stu1.compareTo(stu2));}
}

由于名字是String类,String类在底层中也实现了compareTo方法,所以我们可以直接调用compareTo方法来实现名字的比较。

3. 多个对象之间的比较

多个对象我们可以用一个对应类的数组来存储,然后思路就是让数组里面的元素就行比较。

这里模拟了冒泡排序进行比较。

根据名字来排序

import java.util.Arrays;class Student implements Comparable<Student>{public String name;public int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic int compareTo(Student o) {return this.name.compareTo(o.name);}
}
public class Test {public static void mysort(Comparable[] comparables){for (int i = 0; i < comparables.length-1; i++) {for(int j=0;j<comparables.length-1-i;j++){if(comparables[j].compareTo(comparables[j+1])>0){Comparable tmp=comparables[j];comparables[j]=comparables[j+1];comparables[j+1]=tmp;}}}}public static void main(String[] args) {Student[] students=new Student[]{new Student("zhansan",18),new Student("man",24),new Student("lebron",23)};mysort(students);System.out.println(Arrays.toString(students));}
}

5dbe17b651df48f2862d2f35deb2ae09.png

根据年龄来排序

import java.util.Arrays;class Student implements Comparable<Student>{public String name;public int age;public Student(String name, int age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}@Overridepublic int compareTo(Student o) {return this.age-o.age;}
}
public class Test {public static void mysort(Comparable[] comparables){for (int i = 0; i < comparables.length-1; i++) {for(int j=0;j<comparables.length-1-i;j++){if(comparables[j].compareTo(comparables[j+1])>0){Comparable tmp=comparables[j];comparables[j]=comparables[j+1];comparables[j+1]=tmp;}}}}public static void main(String[] args) {Student[] students=new Student[]{new Student("zhansan",18),new Student("man",24),new Student("lebron",23)};mysort(students);System.out.println(Arrays.toString(students));}
}

c6c90da46f6a4de593d9ef705bc21934.png

 3.总结

1.当前阶段如果我们想要进行自定义类型之间的比较,我们要使用Comparable接口。

2.重写接口里面的方法是我们根据需求来决定如何重写compareTo方法,重写后的compareTo方法里面的具体实现就是我们的比较规则。

2.Comparator接口

我们发现当我们使用Comparable接口时并不是那么灵活,因为它实现的比较规则是写死的,如果我们想要换一种比较规则,我们必须要对实现对比较方法里面的重新构造。

那有没有比较灵活的比较方式呢?答案就是Comparator接口。

AgeComparator类

public class AgeComparator implements Comparator<Student> {@Overridepublic int compare(Student o1, Student o2) {return o1.age- o2.age;}
}

NameComparator类

public class NameComparator implements Comparator<Student> {@Overridepublic int compare(Student o1, Student o2) {return o1.name.compareTo(o2.name);}
}

主函数部分

根据年龄排序

public class Test {public static void main(String[] args) {Student[] students=new Student[]{new Student("zhansan",18),new Student("man",24),new Student("lebron",23)};NameComparator nameComparator=new NameComparator();AgeComparator ageComparator=new AgeComparator();Arrays.sort(students,ageComparator);System.out.println(Arrays.toString(students));}
}

35b307211565411f8fbd235f41347ebe.png

根据名字比较

public class Test {public static void main(String[] args) {Student[] students=new Student[]{new Student("zhansan",18),new Student("man",24),new Student("lebron",23)};NameComparator nameComparator=new NameComparator();AgeComparator ageComparator=new AgeComparator();Arrays.sort(students,nameComparator);System.out.println(Arrays.toString(students));}
}

725a56b1be3a42a2abc0d7ad91f2b4f3.png

这里我们定义了AgeComparator类和NameComparator类,它们都使用了Comparator这个接口,

然后在自己的类里面重写了compareTo方法。

根据以上类实现的对象可以认为是比较规则,将这些对象作为sort函数的参数,就可以灵活实现不同比较方式的转变。

相对于Comparable接口来说,Comparator不需要改变函数内部的具体实现来改变比较规则,只需改变函数的参数就行了,这样更安全也更方便。 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/844889.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

策略模式结合Spring使用

1.抽象策略 /*** 支付方式策略* author Linging* version 1.0.0* since 1.0*/ public interface PayStrategy {void pay(BigDecimal money);}2.具体策略 /*** 支付宝* author Linging* version 1.0.0* since 1.0*/ Component("aliPayStrategy") public class AliPa…

uniapp手机屏幕左滑返回上一页支持APP,H5

核心&#xff1a;touchstart"touchStart" touchend"touchEnd" 代码示例&#xff1a; <template><view class"payPasswordSetting" touchstart"touchStart" touchend"touchEnd"></view> </template&g…

LNMP分布式搭建

一、准备三台主机 192.168.100.11 mysql 192.168.100.12 nginx 192.168.100.13 php 二、关闭防火墙及安全策略 systemctl stop firewalld setenforce 0 三、安装nginx&#xff08;192.168.100.11&#xff09; 1、添加nginx源 vim /etc/yum.repos.d/ng…

618必备好物选购清单有哪些?五款精品好物分享

618将近&#xff0c;很多好物都会在这段时间搞活动&#xff0c;许多朋友会在这个时候置办或者置换家居&#xff0c;那么&#xff0c;2024年的618有哪些值得入手的好物呢&#xff1f;今天&#xff0c;将与大家分享一些精选好物&#xff0c;这些好物在618入手绝对是个不错的选择。…

Unity中模拟生成正态分布的一种方式

using System; using System.Collections; using System.Collections.Generic; using Unity.Mathematics; using UnityEngine;public class MathFunction : MonoBehaviour {private void Start(){//key 范围 0-99 表示 0% 到 99%Dictionary<int,uint> m new Dictionary&…

路径规划中的曲线插值

路径规划中的曲线插值是一种数学方法&#xff0c;它通过一系列离散的点生成一条平滑的曲线&#xff0c;这条曲线可以用于机器人导航、自动车辆驾驶、动画制作等领域。以下是一些常见的曲线插值方法&#xff1a; 线性插值&#xff1a; 线性插值是最简单的插值方法&#xff0c;它…

Leetcode:无重复字符的最长子串

普通版本&#xff08;哈希表 滑动窗口&#xff09; 题目链接&#xff1a;3. 无重复字符的最长子串 - 力扣&#xff08;LeetCode&#xff09; //方法一&#xff1a; class Solution { public:int lengthOfLongestSubstring(string s) {unordered_map<char,int> st;int …

【Linux】文件系统和软硬链接

&#x1f466;个人主页&#xff1a;Weraphael ✍&#x1f3fb;作者简介&#xff1a;目前正在学习c和算法 ✈️专栏&#xff1a;Linux &#x1f40b; 希望大家多多支持&#xff0c;咱一起进步&#xff01;&#x1f601; 如果文章有啥瑕疵&#xff0c;希望大佬指点一二 如果文章对…

Java 服务挂掉,服务器异常宕机问题排查

目录 Java 服务挂掉&#xff0c;服务器异常宕机问题排查一、初步排查1. 检查日志文件2. 查看资源使用情况 二、详细排查1. 内存问题2. CPU 问题3. 磁盘和网络 I/O 三、系统性优化和预防1. 配置监控和报警2. 优化 JVM 参数3. 代码优化 四、案例分享案例一&#xff1a;内存泄漏导…

redux相关源码

1、createStore 实现 2、connct实现 3、bindActionCreators实现 4、Provider实现 5. thunk

html+css web前端 多边形

<!DOCTYPE html><html><head><meta charset"UTF-8"><title>多边形</title><style type"text/css">#pentagon_6_1 {position: absolute;top: 0px;height: 0; width: 100; border-left: 100px solid rgb(255, 255…

【记忆化搜索 】2312. 卖木头块

本文涉及知识点 记忆化搜索 LeetCode2312. 卖木头块 给你两个整数 m 和 n &#xff0c;分别表示一块矩形木块的高和宽。同时给你一个二维整数数组 prices &#xff0c;其中 prices[i] [hi, wi, pricei] 表示你可以以 pricei 元的价格卖一块高为 hi 宽为 wi 的矩形木块。 每…

网络四层、七层协议

一、OSI七层模型 物理层&#xff1a;建立、维护、断开物理连接。 数据链路层&#xff1a;逻辑连接、寻找硬件地址——地址解析协议&#xff1a;ARP、PARP 反向地址转换协议 网络层&#xff1a;寻找逻辑地址&#xff0c;实现不同网络之间的路径选择——ICMP(互联网控制信息协议…

Vue前端平台的搭建

文章目录 前端平台搭建(`Vue2.6`,App:`HBulderX`)创建`Vue2.6`项目下载相应插件方便开发路由配置对连接后端进行一些配置(`main.js`文件)导入ElementUI组件[组件 | Element](https://element.eleme.cn/#/zh-CN/component/icon)同步与异步`axios`异步请求框架前端平台搭建(Vue2.…

YoloV8改进策略:卷积篇|基于PConv的二次创新|附结构图|性能和精度得到大幅度提高(独家原创)

摘要 在PConv的基础上做了二次创新,创新后的模型不仅在精度和速度上有了质的提升,还可以支持Stride为2的降采样。 改进方法简单高效,需要发论文的同学不要错过! 论文指导 PConv在论文中的描述 论文: 下面我们展示了可以通过利用特征图的冗余来进一步优化成本。如图3所…

JVM源码探秘:System.gc全面解析

概述 Java虚拟机&#xff08;JVM&#xff09;的垃圾回收&#xff08;GC&#xff09;通常由VM自身根据预设条件触发&#xff0c;但开发者也可通过特定手段人为触发&#xff0c;比如使用System.gc()、Runtime.gc()或JMap操作等。本文将深入探讨System.gc()的底层原理及其背后的故…

windows 在cmd 使用cd命令无法进入指定目录解决方法

目录预览 一、问题描述二、原因分析三、解决方案四、参考链接 一、问题描述 使用cmd命令想要快速进入某个目录&#xff0c;发现没有跳转&#xff0c;如下&#xff1a; 二、原因分析 cmd 切换目录跨磁盘的话&#xff0c;需要先进行磁盘的转换&#xff0c;也就是要进入到另外一…

使用pkg打包了一个使用了sqlite3的nodejs项目,启动后闪退

从截图来看&#xff0c;问题出在 sqlite3 模块上。说明在打包过程中&#xff0c;sqlite3 模块的 .node 文件没有正确加载。 紧急解决方法&#xff1a; 其实就是exe文件还需要node_modules中的sqlite3 依赖&#xff0c;我们直接在系统顶级放一个node_modules&#xff0c;且其中只…

linux下 搭建Llama3

安装软件&#xff1a; Ollama&#xff0c;官方网站&#xff1a;https://ollama.com/ 可以再下载win、mac和linux版本 linux安装命令为&#xff1a;curl -fsSL https://ollama.com/install.sh | sh 由于我的机器是linux不联网机器&#xff0c;网上没找到下载离线方式&#xff0c…

嵌入式测试基础知识

1.白盒测试也称为结构测试&#xff0c;主要用于检测软件编码过程中的错误。 2.黑盒测试又称为功能测试&#xff0c;主要检测软件的每一个功能是否能够正常使用。 3.软件测试流程&#xff1a;根据测试需求编写测试计划、方案&#xff0c;测试用例&#xff0c;做测试分析&#…