本文將介紹Comparable接口以及,使用其對自定義對象比較大小和排序
下面是Comparable接口的聲明以及作用,可以看到它可以使繼承他的類進行比較大小,只需要調用實現類的compareTo方法即可
public interface Comparable< T >
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.
下面是這個compareTo的定義
就是告訴我們利用
目前對象.compareTo(需要比較的對象)
實現比較大小,
- 如果返回值等於零:o1=o2
- 返回值大於零則o1>o2
- 返回值小於於零則o1<o2
接下來就是例子:
class P implements Comparable<P> {
String name;
int age;
public P(String name,int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(P o) {
return this.age-o.age;
}
}
他很類似Comparator,如果有興趣可以參考java常用類:Comparator
只不過他是需要被我們要排序的類實現,如果我們想要排序一個自定義類,或者讓一個自定義類可以比較大小就需要實現Comparable接口。上面寫完了如何實現接口,下面說一下如何使用接口:
public class ComparableTest {
public static void main(String[] args) {
List<P> personList = new ArrayList<P>();
personList.add(new P("ace",22));
personList.add(new P("xb",21));
personList.add(new P("glm",36));
personList.add(new P("sxy",20));
System.out.println("比較大小");
P ace = new P("ace",22);
P xb = new P("xb",21);
String result = ace.compareTo(xb)==0?"一樣大":ace.compareTo(xb)>0?"ace大":"xb大";
System.out.println(result);
System.out.println("按照年齡");
Collections.sort(personList);
for(P p:personList)
System.out.println(p);
System.out.println();
}
}