What does this code mean?
if( item.compareTo(root.element) < 0 ){
}
I read that:
"Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument."
But I don't don't get it. Can someone explain with an example please?
Take a look at the documentation of the Comparable
interface, which defines the compareTo()
method in the first place. The implementation of this interface in String
follows the same conventions:
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
之前。
it checks if two Strings are equal like this.
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'
如果word1 = item,word2 = root.element并且两者都在字典中,则word1应出现在word2之前。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.