根据源码分析compareTo(String anotherString) 如何按照字段顺序比较的

关于String类中的compareTo(String anotherString);方法,接下来我就两种不同的情况通过源码进行简单分析。
按照字典顺序比较:

   public int compareTo(String anotherString):
 使用当前字符串内容和指定的anotherString按照字典顺序比较
public class StringDemo {
	public static void main(String[] args) {
		String s1 = "hello";
		String s2 = "hel";
		String s3 = "adf";
		//前面字符相同时
		System.out.println(s1.compareTo(s2));
		//前面字符不相同时
		System.out.println(s1.compareTo(s3));
	}
}
当前面字符相同时
String  s1 = "hello";
String s2 = "hel";
System.out.println(s1.compareTo(s2));

通过源码进行分析:

    public int compareTo(String anotherString) {

    int len1 = value.length; 				//字符串1的长度 len1=5
    int len2 = anotherString.value.length;	//字符串2的长度len=3
    int lim = Math.min(len1, len2); 		//两个长度中的最小值  lim=3
    char v1[] = value;						//v1[]={'h','e','l','l','o'}
    char v2[] = anotherString.value;		//v2[]={'h','e','l'}

    int k = 0;								//k=0    k=1    k=2  
    while (k < lim) {						 //  (k<3)   3=3 循环结束
        char c1 = v1[k];					//char c1=v1[0]='h'  c1='e'  c1='l'
        char c2 = v2[k];					//char c2=v2[0]='h'  c2='e'	 c2='l'
        if (c1 != c2) {					
            return c1 - c2;			
        }
        k++;								//k=1   k=2  k=3
    }
    return len1 - len2;						//返回   return len1-len2=5-3=2
}
当前面字符不同时
String  s1 = "hello";
String s3 = "adf";
System.out.println(s1.compareTo(s3));
 public int compareTo(String anotherString) {

    int len1 = value.length; 				//字符串1的长度 len1=5
    int len2 = anotherString.value.length;	//字符串2的长度len=3
    int lim = Math.min(len1, len2); 		//两个长度中的最小值  lim=3
    char v1[] = value;						//v1[]={'h','e','l','l','o'}
    char v2[] = anotherString.value;		//v2[]={'a','d','f'}

    int k = 0;								  
    while (k < lim) {						 //当k=0时
        char c1 = v1[k];					 //c1=v1[0]='h'
        char c2 = v2[k];					 //c2=v2[0]='a'
        if (c1 != c2) {						//满足  (c1 != c2)
            return c1 - c2;					//return c1-c2='h'-'a' 由ASCII可得
  }          								//'h'=104, 'a'=97   
       										//'h'-'a'=104-97=7
        k++;								
    }
    return len1 - len2;						
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值