user2897690
user2897690

Reputation:

Sorting Array in Java by Arrays.sort;

I implemented my own class myclass. I wrote following code for sorting

Arrays.sort(arrayForSortingInterval, new Comparator<myclass>() {
    public int compare(myclass o1, myclass o2) {
        return o1.minute <= o2.minute ? 1 : 0;
    }
});

My array is declared as myclass[] arrayForSortingInterval = new myclass[lengthIntervalArray*2]; and myclass has two integer values minute and tag.

But this sorting code doesn't seem to work.

Upvotes: 0

Views: 273

Answers (4)

njzk2
njzk2

Reputation: 39405

You comparator method is incorrect, since it is not antisymmetric (compare a to b returns 1, then b to a returns 0).

you should simply return o1.minute - o2.minute

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201527

Your compare function is incorrect -1, 0 or 1 for less then, equals or greater respectively.

public int compare(myclass o1, myclass o2) {
  // return o1.minute <= o2.minute ? 1 : 0;
  if (o1.minute < o2.minute) {
    return -1;
  } else if (o1.minute > o2.minute) {
    return 1;
  }
  return Integer.compare(o1.tag, o2.tag);
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

The compare method needs to return a negative number when the left object is less than the right one, zero when the two are equal, and a positive number when the left object is greater than the one on the right. One way of achieving this is calling Integer.compare (assuming that minute is an int in your myclass class):

public int compare(myclass o1, myclass o2) {
    return Integer.compare(o1.minute, o2.minute);
}

Upvotes: 4

Moritz Petersen
Moritz Petersen

Reputation: 13057

Your comparator is wrong. It should: Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Upvotes: 3

Related Questions