Comparison of two words (lines)

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 (result is> 0), equal (result is = 0), or less (result is <0) argument."

But I don’t get it. Can someone explain with an example please?

+4
source share
5 answers

Take a look at the documentation of the Comparable interface, which defines compareTo() . Implementing this interface in String follows the same conventions:

Compares this object with the specified order object. Returns a negative integer, zero, or a positive integer since this object is less than, equal to, or greater than the specified object

This means: if the current line is less than the line accepted as a parameter (in lexicographic order ), we return a negative integer value. If the current string is larger than the string accepted as a parameter, return a positive integer value. Otherwise, the strings are equal and 0 returned.

+5
source

someObject .compareTo ( anotherObject ) returns a negative number if someObject comes before another object.

Here is 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"); } 
+3
source

You would use this in the sort code to find out if item belongs to root.element or not.

+2
source

it checks if two lines are equal.

 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' 
+2
source

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

+2
source

Source: https://habr.com/ru/post/1446838/


All Articles