I am sorting a 2D array by the value of a single column. The first column contains the country code, the second column contains the names of the skaters for this country, the third column contains the score for this country:
skateArray[1][0] = "JPN";
skateArray[1][1] += "Yuzuru HANYU";
skateArray[1][2] = "13";
skateArray[2][0] = "USA";
skateArray[2][1] = "Jeremy ABBOTT "
skateArray[2][2] = "17";
It works for me like this:
Arrays.sort(skateArray, new Comparator<String[]>() {
public int compare(final String[] entry1, final String[] entry2)
{
final String firstScore = entry1[2];
final String secondScore = entry2[2];
return secondScore.compareTo(firstScore);
}
});
for (final String[] string : skateArray) {
System.out.println(string[0] + " " + string[1] + " " + string[2]);
}
Everything works, except for this one quirk at the exit:
GBR 8.0
RUS 37.0
CAN 32.0
USA 27.0
JPN 24.0
ITA 23.0
CHN 20.0
FRA 20.0
GER 17.0
UKR 10.0
As you can see, the country with the lowest score (GBR, 8.0) is displayed first. The rest are displayed in descending order as I want. I can’t understand why.
source
share