当前位置: 首页 > news >正文

Java--常见的接口--Comparable

String类型的compareTo方法:

在String引用中,有一个方法可以比较两个字符串的大小:

和C语言中是一样的,两个字符串一个字符一个去比较。

那么这个方法是怎么实现的呢?

其实就是一个接口:Comparable接口里面的compareTo方法。

也就是如果能扩展这个接口,然后重写这个方法我们也可以在不同的类中实现自己想实现的方法。

比较两个学生年龄大小:

   @Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.age- student.age;}

 比较两个学生名字长短:
 

    //比较两个学生名字大小:@Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.name.compareTo(student.name);}

在main方法中测试:

用名字比较:

    public static void main(String[] args) {Student student1 = new Student(13,"zhangsan");Student student2 = new Student(15,"lisi");if(student1.compareTo(student2)>0){System.out.println("student1>student2");}else{System.out.println("student1<=student2");}}


用年龄比较:

两个结果是不一样的。

自写排序方法:

        我们可以借助该方法写一个排序方法:
 

    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] > comparables[j+1]) {if (comparables[j].compareTo(comparables[j + 1]) > 0) {//交换Comparable tmp = comparables[j];comparables[j] = comparables[j + 1];comparables[j + 1] = tmp;}}}}

用多态写是比较合理的!

当然也可以不用多态:

@Overridepublic int compareTo(Object o) {Student student = (Student) o;return this.name.compareTo(student.name);}public static void mySort(Student[] students){for(int i = 0;i<students.length-1;i++) {for (int j = 0; j <students.length-i-1; j++) {if(students[j].compareTo(students[j+1])>0){Student tmp = students[j];students[j] = students[j+1];students[j+1] = tmp;}}}}

建议用多态!!

http://www.lryc.cn/news/437631.html

相关文章:

  • luogu基础课题单 入门 上
  • 物理设计-物理数据模型优化策略
  • 产学研合作赋能产业升级新动能
  • uniapp tabBar不显示
  • 论文阅读《Robust Steganography for High Quality Images》高质量因子图片的鲁棒隐写
  • node前端开发基本设置
  • 深入掌握:如何进入Docker容器并运行命令
  • 把设计模式用起来(3)用不好的原因之时机不对
  • 【机器学习随笔】基于kmeans的车牌类型分类注意点
  • matlab处理函数3
  • 跨系统环境下LabVIEW程序稳定运行
  • 开源项目低代码表单FormCreate中通过接口加载远程数据选项
  • k8s的搭建
  • 人工智能与机器学习原理精解【19】
  • DingoDB:多模态向量数据库的实践与应用
  • 03.01、三合一
  • github上clone代码过程
  • ChatGLM3模型搭建教程
  • 多层建筑能源参数化模型和城市冠层模型的区别
  • 27. Redis并发问题
  • JVM四种垃圾回收算法以及G1垃圾回收器(面试)
  • Python 数学建模——Vikor 多标准决策方法
  • 计算机网络八股总结
  • AMD CMD UMD CommonJs ESM 的历史和区别
  • 人工智能数据基础之微积分入门-学习篇
  • 【PSINS】ZUPT代码解析(PSINS_SINS_ZUPT)|MATLAB
  • 多态(上)【C++】
  • 如何驱动一枚30年前的音源芯片,YMF288驱动手记 Part2
  • yarn webpack脚手架 react+ts搭建项目
  • 防蓝光护眼灯有用吗?五款防蓝光效果好的护眼台灯推荐