当前位置:网站首页>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 .
边栏推荐
- Ultimate doll 2.0 | cloud native delivery package
- 异步线程池在开发中的使用
- 【开源之美】nanomsg(2) :req/rep 模式
- 飞盘,2022年“黑红”顶流
- B+ tree index use (6) leftmost principle -- MySQL from entry to proficiency (18)
- Oom caused by improper use of multithreading
- Kubelet CRI container runtime
- 天津市应急局与驻津央企签署协议深化应急联动机制建设
- Leetcode 217. there are duplicate elements
- B+ tree (4) joint index -- MySQL from entry to proficiency (16)
猜你喜欢

Kubernetes flannel: host-gw mode

postgresql官网下载出错

Implementation of SAP ABAP daemon

El table implements editable table
Exploration on cache design optimization of community like business

基于Bézier曲线的三维造型与渲染

Brief introduction of reflection mechanism

时间复杂度和空间复杂度

panic: Error 1045: Access denied for user ‘root‘@‘117.61.242.215‘ (using password: YES)

JSON data transfer parameters & date type parameter transfer
随机推荐
Leetcode 263. ugly number
图扑 3D 可视化国风设计 | 科技与文化碰撞炫酷”火花“
【开源之美】nanomsg(2) :req/rep 模式
Can I take your subdomain? Exploring Same-Site Attacks in the Modern Web
The use of asynchronous thread pool in development
[applet] why can't the onreachbottom event be triggered? (one second)
Huawei computer test ~ offset realizes string encryption
Solution: unable to load the file c:\users\user\appdata\roaming\npm\npx PS1, because running scripts is prohibited on this system.
[turn] judge the relationship between two geometries in ArcGIS
One stroke problem (Chinese postman problem)
Kubernetes apiserver current limiting strategy
The serialization class in unity is in JSON format
JUC总结
Sword finger offer (21): push in and pop-up sequence of stack
Probability theory and mathematical statistics
AI-理论-知识图谱1-基础
B+ tree (5) introduction to MyISAM -- MySQL from getting started to mastering (17)
Niuke brush sql---2
B+树挑选索引(1)---mysql从入门到精通(二十二)
Some practical operations of vector