0

私はしばらくこれをやろうとしていましたが、できません。

デフォルトの昇順を降順に変更するにはどうすればよいですか?さらに、配列を並べ替える簡単な方法は他にありますか?

HighScore[] highscorelist = new HighScore[10]; // An array of 10

void setup() {
  size(800, 600);

  // score.txt is:
  //10  -
  //0   -
  //0   -
  //3   b

  String rows[] = loadStrings("scores.txt");

  for (int i = 0; i < highscorelist.length; i ++ ) { // Initialize
    String[] pieces = split(rows[i], TAB);
    highscorelist[i] = new HighScore(parseInt(pieces[0]), pieces[1]);
  }
  Arrays.sort(highscorelist, new SortHighScore());
}

void draw() { 
  fill(0);
  textSize(18);
  text("High Scores", 360, 234);
  text("Name", 300, 260);
  text("Score", 460, 260);
  int x = 320;
  int y = 290;


  //Arrays.sort(highscorelist, new SortHighScore("score"));
  for (int i =0; i < 10; i++) {
    highscorelist[i].display(x, y, 150);
    y+=20;
  }
}


class HighScore {
  int score;
  String name;

  HighScore() {
  }

  HighScore(int tempscore, String tempname) {
    score = tempscore;
    name = tempname;
  }

  void display(int x, int y, int gapX) {
    text(score, x+gapX, y);
    text(name, x, y);
  }
}

class SortHighScore extends HighScore implements Comparator {

  SortHighScore() {
  }

  /*
    method which tells how to order the two elements in the array.
   it is invoked automatically when we call "Arrays.sort", and must be included in this class.
   */
  int compare(Object object1, Object object2) {

    // cast the objects to your specific object class to be sorted by
    HighScore row1 = (HighScore) object1;
    HighScore row2 = (HighScore) object2;


    // necessary to cast to Integer type when comparing ints
    Integer val1 = (Integer) row1.score;
    Integer val2 = (Integer) row2.score;

    // the "compareTo" method is part of the Comparable interface, and provides a means of fully ordering objects.
    return val1.compareTo(val2);
  }
}
4

3 に答える 3

4
Arrays.sort(array,Collections.reverseOrder());
于 2012-12-28T19:01:52.843 に答える
1

すでにコンパレータが書かれているので、この行を変更してください

return val1.compareTo(val2);

return val2.compareTo(val1);

降順で並べ替えます。

于 2012-12-28T19:02:17.463 に答える
0

Arraysクラスを使用して並べ替えます。インブイトソート機能があります

于 2012-12-28T19:03:50.680 に答える