Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

java - Android sort array

i have a string array consisting of a name and a score. I want to sort that array by score. Problem is, considering it's a string array, the scores are strings which results in 13,16,2,5,6 and not 2,5,6,13,16. I am using this code:

int spaceIndex;
String[][] scoreboard;
String[] playername;
String[] score;
int sbsize;

array1.add("Thomas" + ":" + 5);
array1.add("Blueb" + ":" + 6);
array1.add("James" + ":" + 16);
array1.add("Hleb" + ":" + 13);
array1.add("Sabbat" + ":" + 2);
sbsize = array1.size();
scoreboard = new String[sbsize][2];
playername = new String[sbsize];
score = new String[sbsize];
pos2 = new int[sbsize];

for (int i=0; i<array1.size(); i++)
{
    spaceIndex =  array1.get(i).indexOf(':'); 
    scoreboard[i][0] = array1.get(i).substring(0, spaceIndex);
    scoreboard[i][1] = array1.get(i).substring(spaceIndex+1, array1.get(i).length());
}

Arrays.sort(scoreboard, new Comparator<String[]>() {
 @Override
 public int compare(String[] entry1, String[] entry2) {
    String time1 = entry1[1];
    String time2 = entry2[1];
    return time1.compareTo(time2);
    }
 });

What is the solution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Cast them to int. As I recall, something like...

Arrays.sort(scoreboard, new Comparator<String[]>() {
     @Override
     public int compare(String[] entry1, String[] entry2) {
        Integer time1 = Integer.valueOf(entry1[1]);
        Integer time2 = Integer.valueOf(entry2[1]);
        return time1.compareTo(time2);
        }
     });

Also you can make simple value object class for easier manipulations. Like...

class Player
{
  public String name;
  public int score;
}

And after that you can make

 Player[] scoreboard = ...
 Arrays.sort(scoreboard, new Comparator<Player>() {
          @Override
          public int compare(Player player1, Player player2) {
              if(player1.score > player2.score) return 1;
              else if(player1.score < player2.score) return -1;
              else return 0;            
             }
 });

Edit: I recommend you to understand the basic OOP principles, this will help you a lot in the beginning.

Edit 2: Java 8 (with functional interface and a lambda):

Arrays.sort(scoreboard, (player1, player2) -> {
  Integer time1 = Integer.valueOf(player1[1]);
  Integer time2 = Integer.valueOf(player2[1]);
  return time1.compareTo(time2);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...