这段代码是什么意思?
if( item.compareTo(root.element) < 0 ){
}
我读到了:
“按字典顺序比较两个字符串。返回一个表示的整数 该字符串是否大于(结果为> 0),等于(结果 是= 0),或小于(结果是<0)参数。“
但我不明白。有人可以用一个例子解释一下吗?
答案 0 :(得分:5)
查看Comparable
界面的文档,该界面首先定义了compareTo()
方法。 String
中此接口的实现遵循相同的约定:
将此对象与指定的订单对象进行比较。返回负整数,零或正整数,因为此对象小于,等于或大于指定对象
这意味着:如果当前字符串小于,则作为参数接收的字符串(在lexicographical order下)返回负整数值。如果当前字符串大于作为参数接收的字符串,则返回正整数值。否则,字符串相等,并返回0
。
答案 1 :(得分:3)
someObject 。 compareTo ( anotherObject )如果 someObject 位于 anotherObject <之前,则返回负数/ em>的
这是一个比较String对象的例子:
if ("apple".compareTo("zebra") < 0) {
System.out.println("I will be printed");
}
else {
System.out.println("I will NOT be printed");
}
答案 2 :(得分:2)
您可以在排序代码时使用它来查看item
之前是否属于root.element
。
答案 3 :(得分: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'
答案 4 :(得分:2)
如果word1 = item,word2 = root.element并且两者都在字典中,则word1应出现在word2之前。