0
import java.util.Comparator;
public class CompareTester {
int i;
public static class Inside implements Comparator<CompareTester> {
    @Override
    public int compare(CompareTester o1, CompareTester o2) {
        // TODO Auto-generated method stub
        System.out.println(o1.i - o2.i);
        return 0;
}}}

public class CompareTest {
public static void main(String[] args) {
    CompareTester j = new CompareTester();
    j.i = 3;
    CompareTester k = new CompareTester();
    k.i = 5;
    CompareTester l = new CompareTester();
    l.i = 7;
    CompareTester[] numbers = { j, k, l };
    Arrays.sort(numbers, new CompareTester.Inside());
}}

These are two classes that are giving two different results in CompareTester class when ran in Java 6 and Java 7.

Is there any different kind of implementation that has been introduced in Java7 for Comparator?

Krishna
  • 49
  • 1
  • 2
  • 8

2 Answers2

4

Java 7 uses TimSort, Java 6 used MergeSort. Your comparator always returns 0 which breaks the Comparable Contract and TimSort is picking up on that.

To fix the code you really need to address that. If you really want to use the old sort algorithm then compile with -Djava.util.Arrays.useLegacyMergeSort=true

user3757014
  • 222
  • 1
  • 3
3

Apart from a different sorting algorithm, which is only relevant internally, there are no difference between the final result of Array.sort(E, Comparator). So, no, there is not difference "introduced in Java7 for Comparator".

Just change your implementation to

import java.util.Comparator;
public class CompareTester {
    int i;
    public static class Inside implements Comparator<CompareTester> {
        @Override
        public int compare(CompareTester o1, CompareTester o2) {
            return o1.i - o2.i;
        }
    }
}

and compare the final resulting array instead and you'll see that there is no difference between Java 6 and 7.

Edit

If you want to avoid using a Comparator, then make your CompareTester class implement Comparable<T> instead (Java 7 doc here);

import java.lang.Comparable;
public class CompareTester implements Comparable<CompareTester> {
    int i;

    public int compareTo(CompareTester o) {
        return this.i - o.i;
    }
}

Then, you don't need anything special with Array.sort :

Arrays.sort(numbers);
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • Thanks for the reply. Here different sorting algorithm is irrelevant because I am just using integers. But in actual application code I am using objects which I have to override compare method to compare the objects. This is causing an issue. – Krishna Jul 11 '14 at 15:05
  • If you're comparing two `Object`s, as in `obj1 == obj2`, then take a look at [this answer](http://stackoverflow.com/questions/16069106/how-to-compare-two-java-objects); you should override `.equals` and `.hashCode`. For sorting, then implementing the `Comparable` interface is the correct way to go. – Yanick Rochon Jul 11 '14 at 17:47