4

这段代码是什么意思?

if( item.compareTo(root.element) < 0 ){

   }

我读到:

“按字典顺序比较两个字符串。返回一个整数,指示此字符串是大于(结果为 > 0)、等于(结果为 = 0)还是小于(结果为 < 0)参数。”

但我不明白。有人可以举个例子吗?

4

5 回答 5

5

看一下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.

于 2012-11-19T00:22:10.243 回答
3

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");
}
于 2012-11-19T00:25:11.263 回答
2

您将在对代码进行排序时使用它来查看item之前是否属于root.element

于 2012-11-19T00:21:13.387 回答
2

它检查两个字符串是否像这样相等。

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'   
于 2012-11-19T00:21:42.117 回答
2

If the word1= item, and word2= root.element and both are in a dictionary, word1 should appear before word2.

于 2012-11-19T00:27:20.090 回答