gpt4 book ai didi

java - Java中的CompareTo函数在这种情况下做什么

转载 作者:行者123 更新时间:2023-12-01 20:21:24 26 4
gpt4 key购买 nike

public static void main(String[] args) {
System.out.print("Comparing \"axe\" with \"dog\" produces ");
// I don't understand what this does.
int i = "axe".compareTo("dog");
System.out.println(i);

System.out.print("Comparing \"applebee's\" with \"apple\" produces ");
// neither this.
System.out.println( "applebee's".compareTo("apple") );


}

当我运行代码时,它出现 -3,下一个是 5,我不明白如何比较字母并得出数字。“applebee”和“dog”甚至不是字符串变量这是学校的作业,地址为 this链接

最佳答案

在练习之前,我的建议是阅读文档。在本例中,Oracle 引用资料清楚地解释了正数和负数的原因:

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.

这里解释了为什么 -3 和 +5:

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 - Java中的CompareTo函数在这种情况下做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44619004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com