Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading