String的compareTo其實就是依次比較兩個字符串ASC碼。如果兩個字符的ASC碼相等則繼續後續比較,否則直接返回兩個ASC的差值。如果兩個字符串完全一樣,則返回0。來看一下代碼。
public int compareTo(String anotherString) {
int len1 = count;
int len2 = anotherString.count;
//獲取到兩個字符串的較短的長度
int n = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
if (i == j) {
int k = i;
int lim = n + i;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
//如果兩個字符的ASC不相同,則直接返回
if (c1 != c2) {
return c1 - c2;
}
k++;
}
}
else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
//如果兩個字符的ASC不相同,則直接返回
if (c1 != c2) {
return c1 - c2;
}
}
}
//如果都一樣,返回兩個字符串的長度查
return len1 - len2; }
根據上面的代碼,我們可以很方便的計算吃兩個字符串的comperTo的值:
"abcd".compareTo("adef")== -2
"abc".compareTo("abcdef")== -3
"abc".compareTo("abc") == 0
但一直在想着compareTo可以用於實際中什麼應用呢??我這裏例舉使用compareTo進行簡單 字符串的排序。(例如使用compareTo 進行姓名的排序)
//需要進行排序的字符串
String[] array = new String[] { "lilei", "libai", "james", "poly",
"wobfei" };
//使用簡單的循環排序
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i].compareTo(array[j]) > 0) {
String temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
使用上面針對String的排序以後,字符串的內容將會是:
james libai lilei poly wobfei