-3

/* What values are return when I mention return 1, -1 and 0 in the method

I was writing thing this code to sort String based on there size */

public int compare(String s1, String s2)
{
    int len1 = s1.length();
    int len2 = s2.length();

    if(len1 > len2)
    {
        return 1;
    }
    else if (len1 < len2)
    {
        return -1;
    }
    return 0;
}
Aditya Bhogte
  • 15
  • 1
  • 5
  • look in your analysis and check there. 0 means that s1 and s2 have the same length, -1 means that s1 is longer compared to s2 and 1 means s2 is the longest of the two – Stultuske May 16 '19 at 07:24
  • The sign -1/0/1 = less/equal/greater; returns a comparison of the lengths – Joop Eggen May 16 '19 at 07:24
  • 3
    Possible duplicate of [What do the return values of Comparable.compareTo mean in Java?](https://stackoverflow.com/questions/3767090/what-do-the-return-values-of-comparable-compareto-mean-in-java) – Ivar May 16 '19 at 07:28
  • Thanks i got it, basically yes it was 1 if s1 was greater, 0 if both are equal and -1 if s1 is smaller then s2. Thanks for the help everyone – Aditya Bhogte May 17 '19 at 05:47

1 Answers1

3

The javadoc (for the Comparable interface) is pretty clear about the "generic" meaning of these 3 numbers:

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.

And -1, 0, 1 are simply ideal values to get you to that "less than 0, 0 and positive integer" part. So probably the method shown here is simply following that "contract".

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • indeed, but the code shown is not an implementation for Comparable. Comparable accepts one param, and has the method name compareTo – Stultuske May 16 '19 at 07:49
  • 1
    @Stultuske Indeed! I slightly reworded the initial sentence, it should make more sense now! – GhostCat May 16 '19 at 07:58