Java compareTo一步一步执行

时间:2017-03-23 06:51:35

标签: java string

我基本了解Java compareTo方法lexicographically compares两个字符串。 我在这里阅读了基础String Comparison in Java

我有以下示例:

public class CompareTo {
   public static void main(String args[]) {
       String str1 = "String";
       String str2 = "compareTo";
       String str3 = "String";
       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);
   }
}

我得到var1 = -16var2 = 0

如果有人一步一步解释我Lexicographic comparison这将会有很大的帮助。

感谢。

2 个答案:

答案 0 :(得分:1)

好吧,如果你打印:

System.out.println ('S'-'c');

你得到-16

String' compareTo一次比较两个String个字符。第一对不相等的字符(在您的情况下' S'"字符串"' c'" compareTo")确定结果。从字典上看,' S'在' c'之前,比较返回一个负值,这意味着" String"应该来之前" compareTo"。

在第二次比较中,所有字符对都相等,因此compareTo返回0.

答案 1 :(得分:1)

来自Java DOC

public int compareTo(String anotherString)
Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.
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()

在ASCII表中c = 99(十进制)和S = 83(十进制)

表示:S - c = -16