1

この投稿に従って、カスタマイズされたクラスを保持する配列リストをソートする新しいコンパレータを定義しようとしました。私のコードは次のとおりです。

public class mainClass{

    public class match {
    /*I defined a new class to hold some data points*/
        public int x;
        public int y;
        public int score;

        public match(){
            /*initialize values of match if needed*/
        }
    }

    public ArrayList<match> matchList=new ArrayList<match>(); //the arraylist that holds data

    /*code that fills the list with matches*/

    /*the following method is supposed to sort the matchlist. a match with higher score is bigger, and with the same score, a match with bigger x is bigger*/

    public void sortMatchlist(){
    Collections.sort(this.matchList,new Comparator<match>(){
        @Override
        public int compare(match o1, match o2) {
        if(o1.score>o2.score)   return 1;
            else if(o1.score==o2.score){
                if(o1.x>o2.x)   return 1;
                else return 0;
            }
            else    return 0;
        }
    });
}

ただし、メインで sortMatchList() を呼び出したとき、一致リストは変更されていないようです。何が悪いのかわかりません。誰かが私にいくつかの提案をしてもらえますか? 前もって感謝します

4

2 に答える 2

5

これは仕事をするはずです:

if (o1.score == o2.score) {
    return o1.x - o2.x;
} else {
    return o1.score - o2.score;
}

の出力はcompare、1、-1、または 0 である必要はありません。次数を表すには、正、ゼロ、または負でなければなりません。xしたがって、 orの差を返すだけの方が明確だと思いますscore

ちなみに、Java の命名規則によれば、クラス名は大文字で始めるmatch必要があるため、クラスの名前はMatch.

于 2013-03-30T01:18:09.250 に答える
3

ロジックは次のようになります。

if(o1.score > o2.score) return 1;
if(o1.score < o2.score) return -1;
// Scores are equal - compare the "x"-s
if(o1.x > o2.x) return 1;
if(o1.x < o2.x) return -1;
return 0;

あなたの現在のコードはタイブレークを正しく行いません:0スコアが等しい場合に返されますがo1.x < o2.x、アイテムの並べ替え順序が正しくありません。

于 2013-03-30T01:18:57.127 に答える