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