简体   繁体   中英

Arrays.sort (Comparator) - Java 6 vs Java 7

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM