简体   繁体   English

为什么 System.out.println(“0:00”.compareTo(“0”)); 结果是3?

[英]Why does System.out.println(“0:00”.compareTo(“0”)); result in 3?

I am really curious.我真的很好奇。

Why does System.out.println("0:00".compareTo("0"));为什么 System.out.println("0:00".compareTo("0")); result in 3?结果是3? I was expecting 10 as the ASCII code for: 58 and the ASCII code for 0 is 48.我期待 10 作为 ASCII 码:58,而 0 的 ASCII 码是 48。

Please read the documentation to String.compareTo :请阅读String.compareTo的文档:

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

If they have different characters at one or more index positions, let k be the smallest such index;如果它们在一个或多个索引位置具有不同的字符,则设 k 为此类索引中的最小; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string.然后,在 position k 处的字符具有较小值的字符串,由使用 < 运算符确定,按字典顺序位于另一个字符串之前。 In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:在这种情况下, compareTo 返回两个字符串中 position k 处的两个字符值的差值——即值:

 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.如果没有索引 position 不同,则较短的字符串按字典顺序排列在较长的字符串之前。 In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:在这种情况下, compareTo 返回字符串长度的差值——即值:

 this.length()-anotherString.length()

First charater of the first string is equal to the whole second string ( "0" ).第一个字符串的第一个字符等于整个第二个字符串( "0" )。 Therefore they are compared by their lengths.因此,它们按长度进行比较。 The first string is 4 characters long, and the second is 1. Therefore difference is 3第一个字符串是 4 个字符长,第二个是 1。因此差异是3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM