简体   繁体   中英

Sorting data of any type using the Comparable interface

I am trying to write a simple sort function that can sort data of any type using the Comparable interface. I think I have done that, but I am having problems passing arrays of specific types as arguments. The code is

public class Main {
    public static void main(String[] args) {
        int[] arr= {12,14,11,6};
            // The above gives error
            // But this works : Comparable[] arr= {12,14,11,6};
        Comparable b[]= Selection.sort(arr);
        for (Comparable x:b)
            System.out.println(x);
    }
}

What is the probelm ? The error reads : Comparable is a raw type. References to generic type Comparable<T> shoulb be parameterized. Comparable is a raw type. References to generic type Comparable<T> shoulb be parameterized.

Just to make it more clear, the remaining code is:

public class Selection {

    public static Comparable[] sort(Comparable[] a){
        int N= a.length;

        for(int i=0;i<N;i++){
            int min=i;
            for(int j=i+1;j<N;j++)
                if(less(a[j],a[min]))
                    min=j;

            exch(a,i,min);
        }
        return a;
    }

    // Other methods defined here
}

If they are comparable, don't reinvent the wheel!

Arrays.sort(b);

You could wrap it in your method:

public static Comparable[] sort(Comparable[] a){
    Arrays.sort(a);
    return a;
}

But you are adding no value. Just use Arrays.sort(array); where you need it.


If you want to preserve the original array, then make a copy first, also using the Arrays utility class:

Comparable[] sorted = Arrays.copyOf(array);
Arrays.sort(sorted);

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