java比较器的基本实现有两种方式,一种是直接实现Comparable接口,一种是建立一个Comparator
两种方式差不多,但比较的结果却有不一样之处
Main.java
import java.util.Arrays;
import com.enson.chan.Person;
public class Main {
public static void main(String[] args) {
Person person[] = { new Person(10, 120), new Person(18, 100),
new Person(13, 100), new Person(15, 90) };
for(Person per:person){
System.out.println(per);
}
System.out.println("=======");
//此处使用的是Comparable比较器方式
Arrays.sort(person);
for(Person per:person){
System.out.println(per);
}
}
}
直接实现Comparable
package com.enson.chan;
public class Person implements Comparable<Person> {
private int age;
private int height;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public Person(int age, int height) {
super();
this.age = age;
this.height = height;
}
@Override
public int compareTo(Person person) {
if (this.getAge() > person.getAge()) {
return 1;
} else if (this.getAge() < person.getAge()) {
return -1;
} else {
return 0;
}
}
@Override
public String toString(){
return this.getAge()+"|"+this.getHeight();
}
}
设计PersonComparator,此时的Person中不需要有compareTo方法
package com.enson.chen;
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person arg0, Person arg1) {
if (arg0.getAge() > arg1.getAge()) {
return -1;
} else if (arg0.getAge() < arg1.getAge()) {
return 1;
} else {
return 0;
}
}
}
运行结果:
10|120
18|100
13|100
15|90
=======
10|120
13|100
15|90
18|100