当前位置:网站首页>Natural sorting: comparable interface, customized sorting: the difference between comparator interface
Natural sorting: comparable interface, customized sorting: the difference between comparator interface
2022-07-27 16:59:00 【Not very [email protected]】
Catalog
1、 Natural ordering 、 Realization Comparable Interface
1. The first step is to define a test class
2. Realization Comparable Interface , rewrite compareTo Method
2、 Custom sort : Realization Comparator Interface
1、 Natural ordering 、 Realization Comparable Interface
1、 image string, integer When the wrapper class realizes Comparable Interface , Rewrote compareTo(obj) Method , The sorting method of comparing the size of two objects is given
2、 image string 、 The wrapper class overrides compareTo() After method , From small to large
3、 rewrite compareTo(obj) The rules of :
If the current object this Greater than the formal parameter object obj, Then return a positive integer , If the current object this Less than parameter object obj, Returns a negative number , If two objects are equal, return 0;
1. The first step is to define a test class
package demo421.demo04;
import java.util.Comparator;
/**
* @ founder xiaoliu
* @ Creation time 2022/4/23
* @ describe
*/
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public Person(){}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2. Realization Comparable Interface , rewrite compareTo Method
public class Person implements Comparable @Override
public int compareTo(Object o) {
if (o instanceof Person){
Person p1 = (Person) o;
// Mode one :
/*
if (this.age>p1.age){
return 2;
}else if (this.age< p1.age){
return -1;
}else {
return this.name.compareTo(p1.name);
}
*/
/* Mode two : Use packaging compare() Method
public static int compare(int var0, int var1) {
return var0 < var1 ? -1 : (var0 == var1 ? 0 : 1);
}*/
if (this.name == p1.name){
return Integer.compare(this.age,p1.age);
}else{
return this.name.compareTo(p1.name);
}
}
throw new RuntimeException(" The type of input does not match ");
}
// Comparison method 1 : Manual comparison age Size , Then compare name
/*
if (this.age>p1.age){
return 2;}else if (this.age< p1.age){
return -1;
}else {
return this.name.compareTo(p1.name);
}// It's easier to understand it in this way
*/
/* Mode two : Use packaging compare() Method , Because the wrapper class overrides compare() Method , So you can use it directly .
compare Source code :public static int compare(int var0, int var1) {
return var0 < var1 ? -1 : (var0 == var1 ? 0 : 1);
}*/// Compare names first name, Compare your age age
if (this.name == p1.name){ return Integer.compare(this.age,p1.age); }else{ return this.name.compareTo(p1.name); }// It's simpler to write code like this
Test code
package demo421.demo04;
import javax.lang.model.element.VariableElement;
import java.util.Arrays;
/**
* @ founder xiaoliu
* @ Creation time 2022/4/23
* @ describe
*/
public class Demo01 {
public static void main(String[] args) {
Person p1 = new Person("lwh", 20);
Person p2 = new Person("ll", 20);
Person p3 = new Person("ll", 32);
Person p5 = new Person("ll", 21);
Person p4 = new Person("bzd", 23);
Person[] a = new Person[]{p1,p2,p3,p4,p5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
}
}
Method 1 test results
Compare first age Compare again name, The test result is correct
[Person{name='ll', age=20}, Person{name='lwh', age=20}, Person{name='ll', age=21}, Person{name='bzd', age=23}, Person{name='ll', age=32}]
Method 2 test results
Compare first name, Compare again age, The test result is correct
[Person{name='bzd', age=23}, Person{name='ll', age=20}, Person{name='ll', age=21}, Person{name='ll', age=32}, Person{name='lwh', age=20}]
2、 Custom sort : Realization Comparator Interface
1、 background :
When the type of an element is not implemented java.lang.Comparable Interface and not convenient to modify the code ,
Or it does java.lang.Comparable The interface's collation is not suitable for the current operation ,
Then consider using Comparator To sort objects
Test code
package demo421.demo04;
import javax.lang.model.element.VariableElement;
import java.util.Arrays;
import java.util.Comparator;
public class Student {
protected String name;
protected int age;
public Student(String name,int age){
this.age=age;
this.name=name;
}
public Student(){}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public static void main(String[] args) {
Student s1 = new Student("lwh", 33);
Student s2 = new Student("lwh", 22);
Student s3 = new Student("aaa", 45);
Student[] s = new Student[]{s1,s2,s3};
Arrays.sort(s, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.age > s2.age) {
return 3;
} else if (s1.age < s2.age) {
return -2;
} else {
return s1.name.compareTo(s2.name);
}
}
});
System.out.println(Arrays.toString(s));
}
}
test result

版权声明
本文为[Not very [email protected]]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/208/202207271449228623.html
边栏推荐
- Random number formula random
- mysql视图及存储过程
- Start from scratch blazor server (1) -- project construction
- Database foundation
- 获取当前时间的前N天和前后天的数组列表循环遍历每一天
- codis集群部署
- Layoff quarrel, musk: I'm too hard; Mercilessly open source a public opinion acquisition project; Feature engineering is as simple as parameter adjustment?! Nerf boss shouted that he couldn't move; Cu
- 分享一个网上搜不到的「Redis」实现「聊天回合制」的方案
- Ten thousand words analysis ribbon core components and operation principle
- ES6数组新增属性
猜你喜欢
随机推荐
The 31st --- the 52nd
Json数据的格式使用
Niuke topic -- judge whether it is a complete binary tree or a balanced binary tree
C语言之程序环境和预处理
[paper reading] a CNN transformer hybrid approach for cropclassification using multitemporalmultisensor images
【论文阅读】Transformer with Transfer CNN for Remote-Sensing-ImageObject Detection
Mpc5744p clock module
C language output string in reverse order
Array analog linked list
UML图介绍
从零开始Blazor Server(1)--项目搭建
京东张政:内容理解在广告场景下的实践和探索
Niuke topic -- symmetric binary tree
kubesphere多节点安装出错
log4j.jar和slf4-log4下载链接
In addition to "adding machines", in fact, your micro service can be optimized like this
【论文阅读】A CNN-Transformer Hybrid Approach for CropClassification Using MultitemporalMultisensor Images
OpenCV(三)——图像分割
C语言之函数
JDBC程序实现完整步骤

![How to modify the decoding clock [chapter]](/img/a7/e55346a081fac0887b294b078a28a5.png)




![Jerry's built-in touch parameters for modification [chapter]](/img/6b/38c3ad28a7256e5e41bb444d0993db.png)


