2

Is there a String x that will always return a negative number when x.compareTo(y) is called, for any String y? Similarly, is there an x that will always return a positive number? Thanks.

r123454321
  • 3,323
  • 11
  • 44
  • 63

3 Answers3

5

No. It will always have a case when 0 is returned - thats is string is compared to the same string.

Artem Moskalev
  • 5,748
  • 11
  • 36
  • 55
1

No because x.compareTo(x) is 0 for any x as can be inferred from the source code (and from the assumption that the order should be coherent) :

1174    public int compareTo(String anotherString) {
1175        int len1 = count;
1176        int len2 = anotherString.count;
1177        int n = Math.min(len1, len2);
1178        char v1[] = value;
1179        char v2[] = anotherString.value;
1180        int i = offset;
1181        int j = anotherString.offset;
1182
1183        if (i == j) {
1184            int k = i;
1185            int lim = n + i;
1186            while (k < lim) {
1187                char c1 = v1[k];
1188                char c2 = v2[k];
1189                if (c1 != c2) {
1190                    return c1 - c2;
1191                }
1192                k++;
1193            }
1194        } else {
1195            while (n-- != 0) {
1196                char c1 = v1[i++];
1197                char c2 = v2[j++];
1198                if (c1 != c2) {
1199                    return c1 - c2;
1200                }
1201            }
1202        }
1203        return len1 - len2;
1204    }

Now, if your question was about a minimal and a maximal string, and you accept 0 for a comparison of x with itself, then the same code shows that adding any char to a string makes a "greater" one.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

In Java, a.compareTo(b) will return:

  • A negative int if a < b
  • 0 if a == b
  • A positive int if a > b

I hope this helps

Ricardo
  • 112
  • 3
  • 5
  • 15