当前位置:网站首页>Comparator (interface between comparable and comparator)
Comparator (interface between comparable and comparator)
2022-07-26 13:27:00 【A stream kite CD】
There's something wrong , I hope you can point it out , thank you .
List of articles
Concept
The comparator : Compare two or more data , To determine whether they are equal , Or determine the size relationship and order between them ( From Baidu ).
Java The comparator in is mainly through Realization Comparable And Comparator Two interfaces To achieve
Comparable Interface
Inherit interfaces through classes , In a class CompareTo() Method to copy and complete the comparison
The main implementation statements :
class +implements Comparable<>{
…
public int compareTo(Work o){
return 0;
}
}
Comparison method :
adopt if(){}else{} Statement to determine the return value is -1,1,0 Which of them , When used, you return -1,1,0 To arrange the comparators in order .
Comparable Attention to interface implementation : The implementation location of the interface should be in the location of the class , Such as Worker Class so Comparable The interface should be in Worker In the class implementation .
for example :
public class Worker implements Comparable<Worker> {
......
......
public int compareTo(Worker o) {
if (this.salary <o.salary) {
return 1;
} else if (this.salary>o.salary) {
return -1;
} else {
// If the first condition is equal , The second condition of comparison
if (this.age > o.age) {
return 1;
} else if (this.age < o.age) {
return -1;
} else{
return 0;
}
}
}
Comparable Interface instance :
public class Worker implements Comparable<Worker> {
//public class Worker {
private String name;
private int age;
private float salary;
public Worker(String name, int age, float salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Worker{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
@Override
public int compareTo(Worker o) {
if (this.salary <o.salary) {
return 1;
} else if (this.salary>o.salary) {
return -1;
} else {
if (this.age > o.age) {
return 1;
} else if (this.age < o.age) {
return -1;
} else{
return 0;
}
}
}
}
import java.util.*;
public class WorkerTest extends Worker{
public WorkerTest(String name, int age, float salary) {
super(name, age, salary);
}
public static void main(String[] args) {
List<Worker> list =new ArrayList();
list.add(new Worker(" Zhang San ",30,9000));
list.add(new Worker(" Li Si ",31,12000));
list.add(new Worker(" Wang Wu ",28,9000));
list.add(new Worker(" The king of the three ",23,9000));
list.add(new Worker(" The king 2 ",26,12000));
list.add(new Worker(" Wang Liu ",30,12000));
list.add(new Worker(" Li Meili ",48,12000));
list.add(1,new Worker(" Zhao Liu ",26,3300));
for(int i=0;i<list.size();i++){
if (list.get(i).getName().equals(" Wang Wu ")){
list.remove(i);
}
}
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
// // iterator
// Iterator<Worker> it=list.iterator();
// while(it.hasNext()){
// Worker s=it.next();
// System.out.println(s);
// }
Collections.sort(list); //ComparableTo
// use sort Methods the sorting , The sorting condition is written in ComparaTo Conditions in
System.out.println(" After ordering ");
Iterator<Worker> it1=list.iterator();
while(it1.hasNext()){
Worker s=it1.next();
System.out.println(s);
}
}
}
Execution results :
Worker{name=' Zhang San ', age=30, salary=9000.0}
Worker{name=' Zhao Liu ', age=26, salary=3300.0}
Worker{name=' Li Si ', age=31, salary=12000.0}
Worker{name=' The king of the three ', age=23, salary=9000.0}
Worker{name=' The king 2 ', age=26, salary=12000.0}
Worker{name=' Wang Liu ', age=30, salary=12000.0}
Worker{name=' Li Meili ', age=48, salary=12000.0}
After ordering
Worker{name=' The king 2 ', age=26, salary=12000.0}
Worker{name=' Wang Liu ', age=30, salary=12000.0}
Worker{name=' Li Si ', age=31, salary=12000.0}
Worker{name=' Li Meili ', age=48, salary=12000.0}
Worker{name=' The king of the three ', age=23, salary=9000.0}
Worker{name=' Zhang San ', age=30, salary=9000.0}
Worker{name=' Zhao Liu ', age=26, salary=3300.0}
Comparator( The comparator ) Interface
The main implementation statements :
class +implements Comparator<>{
…
public int compare(Worker o1,Worker o2){
return 0;
}
}
Comparison method :
adopt if(){}else{} Statement to determine the return value is -1,1,0 Which of them , When used, you return -1,1,0 To arrange the comparators in order .
Comparator Attention to interface implementation : The implementation position of the interface should Not in the location of the class , Such as Worker Class so Comparable Interface cannot be in Worker In the class implementation .
Comparator The design of the interface complies with OCP principle .
for example :
public class Worker {
private String name;
private int age;
private float salary;
public Worker(String name, int age, float salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Worker{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
import java.util.Comparator;
public class WorkerComparator implements Comparator<Worker> {
@Override
public int compare(Worker o1, Worker o2) {
if (o1.getSalary() < o2.getSalary()) {
return 1;
} else if (o1.getSalary() > o2.getSalary()) {
return -1;
} else {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
}
}
Comparator Interface instance
public class Worker {
private String name;
private int age;
private float salary;
public Worker(String name, int age, float salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Worker{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
import java.util.Comparator;
public class WorkerComparator implements Comparator<Worker> {
@Override
public int compare(Worker o1, Worker o2) {
if (o1.getSalary() < o2.getSalary()) {
return 1;
} else if (o1.getSalary() > o2.getSalary()) {
return -1;
} else {
if (o1.getAge() > o2.getAge()) {
return 1;
} else if (o1.getAge() < o2.getAge()) {
return -1;
} else {
return 0;
}
}
}
}
import java.util.*;
public class WorkerTest extends Worker{
public WorkerTest(String name, int age, float salary) {
super(name, age, salary);
}
public static void main(String[] args) {
List<Worker> list =new ArrayList();
list.add(new Worker(" Zhang San ",30,9000));
list.add(new Worker(" Li Si ",31,12000));
list.add(new Worker(" Wang Wu ",28,9000));
list.add(new Worker(" The king of the three ",23,9000));
list.add(new Worker(" The king 2 ",26,12000));
list.add(new Worker(" Wang Liu ",30,12000));
list.add(new Worker(" Li Meili ",48,12000));
list.add(1,new Worker(" Zhao Liu ",26,3300));
for(int i=0;i<list.size();i++){
if (list.get(i).getName().equals(" Wang Wu ")){
list.remove(i);
}
}
list.sort(new WorkerComparator());//Comparator
System.out.println(" After ordering ");
Iterator<Worker> it1=list.iterator();
while(it1.hasNext()){
Worker s=it1.next();
System.out.println(s);
}
}
}
Execution results :
Worker{name=' Zhang San ', age=30, salary=9000.0}
Worker{name=' Zhao Liu ', age=26, salary=3300.0}
Worker{name=' Li Si ', age=31, salary=12000.0}
Worker{name=' The king of the three ', age=23, salary=9000.0}
Worker{name=' The king 2 ', age=26, salary=12000.0}
Worker{name=' Wang Liu ', age=30, salary=12000.0}
Worker{name=' Li Meili ', age=48, salary=12000.0}
After ordering
Worker{name=' The king 2 ', age=26, salary=12000.0}
Worker{name=' Wang Liu ', age=30, salary=12000.0}
Worker{name=' Li Si ', age=31, salary=12000.0}
Worker{name=' Li Meili ', age=48, salary=12000.0}
Worker{name=' The king of the three ', age=23, salary=9000.0}
Worker{name=' Zhang San ', age=30, salary=9000.0}
Worker{name=' Zhao Liu ', age=26, salary=3300.0}
Anonymous inner class pairs can also be used Comparator and Comparable Interface simplification
TreeSet<Users> U=new TreeSet(new Comparator<Users>(){
@Override
public int compare(Users o1, Users o2) {
return o1.getName()-o2.getName();
}
});
Use lambda Expression re simplification
TreeSet<Users> U=new TreeSet<Users>((o1,o2)->{
return o1.getName()-o2.getName();
} );
Comparator and Comparable How to choose ?
When the rules of comparison don't change , Or when the rules of comparison are only 1 When it's time , It is suggested that Comparable Interface ; When there are more than one comparison rule , And it requires ordinary switching between multiple comparison rules , It is recommended to use Comparator Interface .
边栏推荐
- How to face scientific and technological unemployment?
- 我们被一个 kong 的性能 bug 折腾了一个通宵
- 冒泡排序的时间复杂度分析
- 估值15亿美元的独角兽被爆裁员,又一赛道遇冷?
- Probability theory and mathematical statistics
- Kubernetes flannel: host-gw mode
- 【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯
- Extra (5) - MySQL execution plan (51)
- Hcip day 11 comparison (BGP configuration and release)
- [flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light
猜你喜欢

天津市应急局与驻津央企签署协议深化应急联动机制建设
![[upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication](/img/d4/c677de31f73a0e0a4b8b10b91e984a.png)
[upper computer tutorial] Application of integrated stepping motor and Delta PLC (as228t) under CANopen communication

同站攻击(相关域攻击)论文阅读 Can I Take Your Subdomain?Exploring Same-Site Attacks in the Modern Web

Photoshop(CC2020)未完

12 brand management of commodity system in gulimall background management

Precautions for triggering pytest.main() from other files

官宣!艾德韦宣集团与百度希壤达成深度共创合作

Kubernetes apiserver current limiting strategy
![[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light](/img/99/6581b8a576e59a13aa4e977e3a1b70.jpg)
[flower carving hands-on] fun music visualization series small project (12) -- meter tube fast rhythm light

解决方案丨5G技术助力搭建智慧园区
随机推荐
Mysql数据目录(1)---数据库结构(二十四)
Outline design specification
Ultimate doll 2.0 | cloud native delivery package
Unicode文件解析方法及存在问题
Photoshop (cc2020) unfinished
B+ tree index use (9) grouping, back to table, overlay index (21)
Why do you want to make "secret comments"?
Square root of leetcode 69. x
时间复杂度和空间复杂度
B+树索引使用(7)匹配列前缀,匹配值范围(十九)
Mysql数据目录(3)---表数据结构myISAM(二十六)
Abstract factory and its improvement examples
JSON format execution plan (6) - MySQL execution plan (52)
Codeforces Round #810 (Div. 2)【比赛记录】
Sword finger offer (IX): abnormal jumping steps
Activity. Onstop() delay 10 seconds? Wonderful investigation process
The serialization class in unity is in JSON format
With 8 years of product experience, I have summarized these practical experience of continuous and efficient research and development
【OAuth2】八、OAuth2登录的配置逻辑-OAuth2LoginConfigurer和OAuth2ClientConfigurer
【花雕动手做】有趣好玩的音乐可视化系列小项目(12)---米管快速节奏灯