一般,Java中通過接口實現兩個對象的比較,比較常用就是Comparable接口和Comparator接口。首先類要實現接口,並且使用泛型規定要進行比較的對象所屬的類,然后類實現了接口后,還需要實現接口定義的比較方法,在這些方法中傳入需要比較大小的另一個對象,通過選定的成員變量與之比較,如果大於則返回1,小於返回-1,相等返回0。
Comparable實現
public class People implements Comparable<People>{
private String name;
private int age;
public People(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(People o) {
// 按年齡從小到大排序
if(this.age > o.getAge()) {
return 1;
} else if (this.age < o.getAge()) {
return -1;
}
// 相等情況
return 0;
}
}
排序測試:
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
People p1 = new People("fei", 35);
People p2 = new People("qiang", 22);
People p3 = new People("sheng", 24);
ArrayList<People> list = new ArrayList<People>();
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list);
for(People p:list) {
System.out.println("name:"+p.getName()+", age:"+p.getAge()+"。");
}
}
}
結果:
name:qiang, age:22。
name:sheng, age:24。
name:fei, age:35。
Comparator實現
import java.util.Comparator;
public class PeopleComparator implements Comparator<People>{
@Override
public int compare(People o1, People o2) {
// 從大到小排序
if(o1.getAge() > o2.getAge()) {
return -1;
} else if (o1.getAge() < o2.getAge()) {
return 1;
}
return 0;
}
}
排序測試:
public class Test {
public static void main(String[] args) {
People p1 = new People("fei", 35);
People p2 = new People("qiang", 22);
People p3 = new People("sheng", 24);
ArrayList<People> list = new ArrayList<People>();
list.add(p1);
list.add(p2);
list.add(p3);
// 指定一個比較器
list.sort(new PeopleComparator());
for(People p:list) {
System.out.println("name:"+p.getName()+", age:"+p.getAge()+"。");
}
}
}
結果:
name:fei, age:35。
name:sheng, age:24。
name:qiang, age:22。
兩種方式比較
1:Comparable是在類內部定義的方法實現的排序,Compartor是在類外部實現的排序。
2: 一個類實現了Comparable接口則表明這個類的對象之間是可以互相比較的,這個類對象組成的集合就可以直接使用sort方法排序。
3:Comparator可以看成一種算法的實現,講算法和數據分離,可以定義多個比較器實現比如升序、降序等。