compareTo()实际返回什么? [英] What does compareTo() actually return?

查看:96
本文介绍了compareTo()实际返回什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的 compareTo()方法返回的值大于/等于/小于0,我知道.但是,价值本身就是我的问题.返回 compareTo()时2或4有什么区别.看下面的代码

The compareTo() method in Java returns a value greater/equal/less than 0 and i know that. However, the value itself is my question. What is the difference between 2 or 4 when compareTo() returns. Look at the code below

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?

Why the last two commands are -5 and -1?

推荐答案

这是字典顺序的定义.如果两个字符串不同,那么它们要么在某个索引处具有不同的字符(这是两个字符串的有效索引),要么它们的长度不同,或者两者都存在.如果它们在一个或多个索引位置具有不同的字符,则令k为此类索引中的最小值;则字符串的位置k处的值较小,这是通过使用<运算符,按字典顺序在另一个字符串之前.在这种情况下,compareTo返回两个字符串中位置k处两个字符值的差,即值:

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)

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

如果在它们之间没有索引位置不同,则较短的字符串在字典上在较长的字符串之前.在这种情况下,compareTo返回字符串长度的差-即值:

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()

this.length()-anotherString.length()

这篇关于compareTo()实际返回什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆