加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – compareTo()实际返回什么?

发布时间:2020-12-15 04:48:36 所属栏目:Java 来源:网络整理
导读:Java中的compareTo()方法返回一个大于/等于/小于0的值,我就知道了.但是,价值本身就是我的问题. compareTo()返回时,2或4之间有什么区别.看下面的代码 String s1="hello"; String s2="hello"; String s3="meklo"; String s4="hemlo"; System.out.println(s1.co
Java中的compareTo()方法返回一个大于/等于/小于0的值,我就知道了.但是,价值本身就是我的问题. compareTo()返回时,2或4之间有什么区别.看下面的代码

String s1="hello";  
String s2="hello";  
String s3="meklo";  
String s4="hemlo";  
System.out.println(s1.compareTo(s2));     // 0
System.out.println(s1.compareTo(s3));     // -5
System.out.println(s1.compareTo(s4));     // -1

为什么最后两个命令是-5和-1?

解决方法

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)

This is the definition of lexicographic ordering. If two strings are different,then either they have different characters at some index that is a valid index for both strings,or their lengths are different,or both. If they have different characters at one or more index positions,let k be the smallest such index; then the string whose character at position k has the smaller value,as determined by using the < operator,lexicographically precedes the other string. In this case,compareTo returns the difference of the two character values at position k in the two string — that is,the value:

this.charAt(k)-anotherString.charAt(k)

If there is no index position at which they differ,then the shorter string lexicographically precedes the longer string. In this case,compareTo returns the difference of the lengths of the strings — that is,the value:

this.length()-anotherString.length()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读