1

I am using the String.compareTo() method for String comparison.

Consider the following code:

String firstLexicon = "0"; 
String anyString = "anyString";
int result = firstLexicon.compareTo(anyString);

What would be the value for firstLexicon so that the method firstLexicon.compareTo(anyString); will always give a negative result for any value except firstLexicon? My best guess was "0".

Manos
  • 151
  • 2
  • 12
  • It can't always give a negative result. At least `firstLexicon.compareTo(firstLexicon);` will return 0 for any value of `firstLexicon`. – Kayaman Jun 06 '16 at 10:49
  • 1
    Could you give us a bigger context? What are you trying to achieve? Maybe `""` could work ok for you? – radoh Jun 06 '16 at 10:52
  • `""` Might be an option. The context is that this value will be used as a start key in HBase, for a reserve scan. What would be the result of `"".compareTo("0");` ? – Manos Jun 06 '16 at 10:56
  • or `"\0"` / `'\0'` (which is a `char` with with value 0, not the character for 0.). It's the next string after `""`. – zapl Jun 06 '16 at 10:58

2 Answers2

2

The empty string ("") is smaller than any other string since the first min(firstLexicon.length(), anyString.length()) (=0) are compared and if that doesn't yield a difference, the shorter String is the lexicographical smaller string.

fabian
  • 80,457
  • 12
  • 86
  • 114
0

firstLexicon should be 0 to achieve what you want, with just one exception, comparing "0" to itself will return a 0

Edit: I was wrong, the correct answer is the empty string ""

SCouto
  • 7,808
  • 5
  • 32
  • 49