我正在尝试编写一个简单的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.
为了使其更清晰,剩下的代码是:
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
}
答案 0 :(得分:3)
如果它们具有可比性,请不要重新发明轮子!
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);