Java comparator sorts single record out of order

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.

+4
source share
3 answers

This is because you are comparing grades as strings, so they are sorted alphabetically.

Try replacing the last line of your function as follows:

return new Double(secondScore).compareTo(new Double(score1));
+6
source

. 8 () 1 (), .

float integer . .

+3

, , String .

- Skater. () . ​​ double int, .

class Skater {
    String country;
    String name;
    double score;
    public Skater(String country, String name, double score){
        this.country = country;
        this.name = name;
        this.score = score;
    }

    @Override public String toString() { return country + " " + name + " " + score; }
}

, :

Skater[] skaters = {
    new Skater("JPN", "Yuzuru HANYU", 13), 
    new Skater("USA", "Jeremy ABBOTT", 17)
}

Arrays.sort(skaters, new Comparator<Skater>(){
    @Override int compare(Skater s1, Skater s2){
        return Double.compare(s1.score, s2.score);
    }
}

for(Skater skater : skaters) {
    System.out.println(skater);
}
+2

Source: https://habr.com/ru/post/1599358/


All Articles