当前位置:网站首页>Use of comparable (for arrays.sort)
Use of comparable (for arrays.sort)
2022-06-25 11:14:00 【User 9854323】
package snippet;
import java.util.Arrays;
/**
* Use Comparable Interface : Let the class of the object to be sorted implement Comparable Interface , And rewrite Comparable Interface compareTo() Method
* The disadvantage is that you can only sort by one rule
* @author tong
*
*/
public class Compara {
public static void main(String[] args) {
Person[] persons = new Person[5];
persons[0] =new Person("tom",45);
persons[1] =new Person("jack",12);
persons[2] =new Person("bill",21);
persons[3] =new Person("kandy",34);
persons[4] =new Person();
// The key
Arrays.sort(persons);
for (Person person:persons) {
System.out.println(person);
}
}
}Here is inheritance Comparable Of Person class :
package snippet;
class Person implements Comparable<Person>{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public Person(){
this("unknown", 0);
}
// rewrite Student Class toString() Method , When you import an object, output it as follows
@Override
public String toString() {
return "Person[name:"+name+",age:"+age+"]";
}
// Override the compareTo() Method , Sort them in descending order
@Override
public int compareTo(Person o) {
return age-o.age;
}
}Output results :
Person[name:unknown,age:0]
Person[name:jack,age:12]
Person[name:bill,age:21]
Person[name:kandy,age:34]
Person[name:tom,age:45]边栏推荐
- 3 Questions par jour (3) - vérifier l'existence d'entiers et de leurs doubles
- 龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书
- MySQL synchronous data configuration and shell script implementation
- 16 种企业架构策略
- Kingbasees plug-in DBMS of Jincang database_ session
- GaussDB 集群维护案例集-sql执行慢
- Daily Mathematics Series 52: February 20
- COSCon'22 讲师征集令
- 基于SSH的高校实验室物品管理信息系统的设计与实现 论文文档+项目源码及数据库文件
- 金仓数据库 KingbaseES 插件DBMS_RANDOM
猜你喜欢

Dell technology performs the "fast" formula and plays ci/cd

Getting started with Apache Shenyu

Sign up to open the third session of the "flying oar hacker marathon". It's been a long time

龙书虎书鲸书啃不动?试试豆瓣评分9.5的猴书

Apache ShenYu 入门

FPGA基于VGA显示字符及图片

软件测试 避免“试用期被辞退“指南,看这一篇就够了

How to start the phpstudy server

Nuxtjs actual combat case

SystemVerilog(十三)-枚举数据类型
随机推荐
Dell technology performs the "fast" formula and plays ci/cd
有关计网的五种类型题
zabbix分布式系统监控
Comparator(用于Arrays.sort)
Daily 3 questions (2) - find out the lucky numbers in the array
今天16:00 | 中科院计算所研究员孙晓明老师带大家走进量子的世界
Is it safe for Guosen Securities to open a securities account
从GEE中免费获取全球人类住区层 (GHSL) 数据集
Jincang database kingbasees plug-in identity_ pwdexp
Five types of questions about network planning
金仓KFS数据集中场景(多对一)部署
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-7
GaussDB 如何统计用户sql的响应时间
Android之Kotlin语法详解与使用
Gaussdb others scenarios with high memory
Multiple environment variables
金仓KFS数据级联场景部署
金仓数据库 KingbaseES 插件force_view
keep-alive
Garbage collection mechanism