在之前的学习中,始终没有搞清楚String中compareTo()方法的实现原理是什么,今天在复习String的相关知识理解了一点点写出来分享一下.
/*
* 按字典顺序比较两个字符串
* int compareTo(String str)
* */
public class StringDemo2 {
public static void main (String [] args){
String s1 = "hellot";
String s2 = "helloworld";
String s3 = "hellow";//compareTo()返回值是遇到第一组不相同的字符时用两个字符的ASCII码差值作为返回结果c1-c2
int t = 't';//116
int w = 'w';//119
System.out.println(s2.compareTo(s1));//3
System.out.println(s1.compareTo(s3));//-3
}
}
题目解析:
我们拿s2.compareTo(s1)为例 下面是解读compareTo()方法底层实现的源码
public int compareTo(String anotherString) {
int len1 = value.length; s2.length = 10
int len2 = anotherString.value.length; s1.length = 6
int lim = Math.min(len1, len2); ( 10, 6) 最小值 6
char v1[] = value; s2=[h ,e ,l, l, o, w, o, r, l, d]
char v2[] = anotherString.value; s1=[h,e,l,l,o,t]
int k = 0;
while (k < lim) { k<6
char c1 = v1[k]; [h,e,l,l,o,w]
char c2 = v2[k];[h,e,l,l,o,t]
if (c1 != c2) {
当执行这条语句时 c1=w c2=t
return c1 - c2; 返回值是:w-t =119-116=3 此时执行结果就是3
}
k++;
}
return len1 - len2;
} 如果两个字符串的每个位置对应的字符都相同的话,compareTo()比较的结果就是两个字符串的差值