java - compareTo() 实际上返回什么?

标签 java string

Java 中的 compareTo() 方法返回一个大于/等于/小于 0 的值,我知道这一点。但是,值(value)本身就是我的问题。 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()

关于java - compareTo() 实际上返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41115079/

相关文章:

java - 为什么递减循环比递增循环运行得快?

java - 如何实现接受超过 15 个参数的方法

python - 如何删除字符串中的字母

java - 自动将测量格式化为 Java 中的工程单位

c# - 将字符串文字分配给 C# 中的字符串

java - Mac L&F 问题 : Differing behavior of JTextField. requestFocus()

java - FileInputStream 只读取文件中的第一个单词

java - 列表<E>实现

java - 现实生活中,在 Java 中使用 String.intern() 的实际示例?

string - 在字符串中的特定位置插入字符