Home > OS >  Self Define CompareTo(), why does the order of compareTo matters to the sorting order?
Self Define CompareTo(), why does the order of compareTo matters to the sorting order?

Time:08-31

I have String array of [3,30,34,5,9] that I want to sort,

However, for value 3 and 30, 3 has to be bigger than 30

such that string a b > b c. if a = 3 and b = 30; ab>ba => 330>303 so that 3 should be bigger than 30;

So that my array [3,30,34,5,9] after sorting should be [9,5,34,3,30]

I found a class function that implements comparator as following:

private class LargerNumberComparator implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
        String order1 = a   b;
        String order2 = b   a;
       return order1.compareTo(order2);
    }
}

In the above code, it will sort my string in ascending order such that original array: [3,30,34,5,9] will become [30,3,34,5,9]

However, if I change the return order1.compareTo(order2); to be return order2.compareTo(order1) that will change the sorting order of the array from ascending to descending;

Q:Why does the order to .compareTo changes the sorting order?

CodePudding user response:

compare(a, b) returns a number that is negative if a < b, zero if a == b, and positive if a > b.

Let's assume compare(a, b) returns a negative number, so a < b.

Then order1.compareTo(order2) returned a negative number too, so order1 < order2.

But if you returned order2.compareTo(order1), well, we know order1 < order2. But that means order2 > order1, so order2.compareTo(order1) will return a positive number.

In general, it's really just that a < b is not the same thing as b < a -- it's the opposite.

CodePudding user response:

The docs for Comparator.compare() says:

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

You can see right there in the docs that order matters. First argument and second argument are different. So if you compare two strings

"a".compareTo( "b" )   // returns negative

The result indicates that a should be less than b. However if you compare the strings this way:

"b".compareTo( "a" ) // returns positive

The result indicates that a is actually greater than b, so you get a being placed after b. In other words, reverse sort order.

  • Related