Issue
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?
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.
Answered By - Louis Wasserman
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)