1

According to this post, I tried defining a new comparator to sort an arraylist holding a customized class. My code is as follows:

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;
        }
    });
}

When I called the sortMatchList() in main however, the matchlist seems to be unchanged. I can't figure out what's wrong. Can somebody give me some suggestions? Thanks in advance

Community
  • 1
  • 1
turtlesoup
  • 3,188
  • 10
  • 36
  • 50

2 Answers2

5

This should do the job:

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

The output of compare doesn't have to be 1, -1 or 0. It just has to be positive, zero, or negative to represent the order. Hence I think it's clearer just to return the difference of x or score.

On a side note, according to naming conventions in Java, class names should begin with capital letters, so your class match should be named Match.

chopchop
  • 1,905
  • 2
  • 22
  • 37
3

The logic should be as follows:

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;

Your current code does not do the tie breaking correctly: it returns 0 when scores are equal, but o1.x < o2.x, making the sort order the items incorrectly.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523