實現(xiàn)Comparable接口下的唯一方法comparaTo()就可以比較類的大小,這些類包括java內(nèi)置的包裝類(Integer類,Character類等)屋群、日期類和自定義的類(當(dāng)然得自己實現(xiàn)Comparable接口还惠,重寫comparaTo方法)。
public interface Comparable<T> {
/**
* @param o the object to be compared.
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
* @throws NullPointerException if the specified object is null
* @throws ClassCastException if the specified object's type prevents it from being compared to this object.
*/
public int compareTo(T o);
}
Integer類的比較,根據(jù)基本數(shù)據(jù)類型比較痕惋。
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
Character類的比較,根據(jù)Unicode編碼順序比較娃殖。Unicode表中值戳,序號30-39是數(shù)字“0,1,2···9”珊随,序號65-90是大寫字母“A述寡,B,C···Z”叶洞,序號97-122是小寫字母“a鲫凶,b,c···z”衩辟。
public int compareTo(Character anotherCharacter) {
return compare(this.value, anotherCharacter.value);
}
public static int compare(char x, char y) {
return x - y;
}
String類的比較螟炫。如果一個字符串是另一個起始開始的子串,返回兩個字符串的長度差艺晴,否則逐個比較字符的Unicode碼大小昼钻,返回不相等時unicode碼之差掸屡。
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
例如abc和aBc比較,返回b和B的Unicode碼之差32(98-66).