繁体   English   中英

使用Comparable接口对任何类型的数据进行排序

[英]Sorting data of any type using the Comparable interface

我正在尝试编写一个简单的sort函数,可以使用Comparable接口对任何类型的数据进行排序。 我想我已经这样做了,但是我在将特定类型的数组作为参数传递时遇到了问题。 代码是

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

什么是probelm? 错误如下: 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.

为了使其更清晰,剩下的代码是:

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
}

如果它们具有可比性,请不要重新发明轮子!

Arrays.sort(b);

可以把它包装在你的方法中:

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

但是你没有增加任何价值。 只需使用Arrays.sort(array); 你需要它的地方。


如果要保留原始数组,请先使用Arrays实用程序类进行复制:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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