这段代码是什么意思?
if( item.compareTo(root.element) < 0 ){
}
我读到:
“按字典顺序比较两个字符串。返回一个整数,指示此字符串是大于(结果为 > 0)、等于(结果为 = 0)还是小于(结果为 < 0)参数。”
但我不明白。有人可以举个例子吗?
这段代码是什么意思?
if( item.compareTo(root.element) < 0 ){
}
我读到:
“按字典顺序比较两个字符串。返回一个整数,指示此字符串是大于(结果为 > 0)、等于(结果为 = 0)还是小于(结果为 < 0)参数。”
但我不明白。有人可以举个例子吗?
看一下Comparable
接口的文档,它首先定义了compareTo()
方法。此接口的实现String
遵循相同的约定:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
This means: if the current string is less than the string received as parameter (under the lexicographical order) return a negative integer value. If the current string is greater than the string received as parameter, return a positive integer value. Otherwise, the strings are equal and 0
is returned.
someObject.compareTo(anotherObject) returns a negative number if someObject comes before anotherObject.
Here's an example that compares String objects:
if ("apple".compareTo("zebra") < 0) {
System.out.println("I will be printed");
}
else {
System.out.println("I will NOT be printed");
}
您将在对代码进行排序时使用它来查看item
之前是否属于root.element
。
它检查两个字符串是否像这样相等。
a>A would return a positive number as `a` is greater than `A`
A>a would return a negetive number as `A` is less than `a`
a==a would return 0 as `a` is equal to `a`
a>Z would return a positive number as 'a' is greater than 'A'
trend> zend would return a positive number as `t` is greater than 'z'
If the word1= item, and word2= root.element and both are in a dictionary, word1 should appear before word2.