假設我們有一個int類型和一個字符串的類。我可以定義該類的一個對象如何與其他對象進行比較。
我可以選擇任何標準。例如,我可能決定根據int進行排序。如果我碰巧有兩個int的具有相同的價值,我可以決定的字符串作爲附加條件,這樣的事情:
// this class *knows* how to "compare" against him self
class CustomObject implements Comparable<CustomObject> {
String aString;
int aInt;
...
public int compareTo(CustomObject two) {
int diff = this.aInt - two.aInt;//<-- compare ints
if(diff != 0) { // they have different int
return diff;
}
return this.aString.compareTo(two.aString);//<-- compare strings...
}
...
}
這裏有一個完整的運行演示...
import java.util.*;
class SortDemo {
public static void main(String ... args) {
// create a bunch and sort them
List<CustomObject> list = Arrays.asList(
new CustomObject(3, "Blah"),
new CustomObject(30, "Bar"),
new CustomObject(1, "Zzz"),
new CustomObject(1, "Aaa")
);
System.out.println("before: "+ list);
Collections.sort(list);
System.out.println("after : "+ list);
}
}
// this class *knows* how to "compare" against him self
class CustomObject implements Comparable<CustomObject> {
String aString;
int aInt;
CustomObject(int i, String s) {
aInt = i;
aString = s;
}
// comparable interface lets you
// specify "HOW" to compare two
// custom objects
public int compareTo(CustomObject two) {
// I migth compare them using the int first
// and if they're the same, use the string...
int diff = this.aInt - two.aInt;
if(diff != 0) { // they have different int
return diff;
}
// else let the strings compare them selves
return this.aString.compareTo(two.aString);
}
public String toString(){
return "CustomObject[aInt="+aInt+", aString="+aString+"]";
}
}
這裏的輸出:
before: [CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=1, aString=Aaa]]
after : [CustomObject[aInt=1, aString=Aaa], CustomObject[aInt=1, aString=Zzz], CustomObject[aInt=3, aString=Blah], CustomObject[aInt=30, aString=Bar]]
我希望這足夠
清楚您也可以通過一個定製協mparator。讓我知道你是否需要一個樣本。
順便說一句,除非你有很好的理由,否則不應該使用'java.util.Vector'。這個類的日期是Java1.1,並且幾乎被'java.util.Arraylist'代替了。 – OscarRyz 2011-02-25 03:18:51
我不知道這個......謝謝! – 2011-02-25 04:37:38
使用像這樣的嵌套if語句不是一個非常好的OO解決方案。你也不能僅僅調用原始數據類型的「compareTo」,所以代碼變得更加複雜。 – camickr 2011-02-25 04:52:49