Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Two Words(Strings)

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?

like image 996
MosesA Avatar asked Dec 08 '22 19:12

MosesA


2 Answers

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.

like image 50
Óscar López Avatar answered Dec 11 '22 07:12

Óscar López


You would use this in sorting code to see if item belongs before root.element or not.

like image 41
John3136 Avatar answered Dec 11 '22 08:12

John3136