[英]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. 我正在尝试编写一个简单的
sort
函数,可以使用Comparable
接口对任何类型的数据进行排序。 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 ? 什么是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.
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);
只需使用
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: 如果要保留原始数组,请先使用
Arrays
实用程序类进行复制:
Comparable[] sorted = Arrays.copyOf(array);
Arrays.sort(sorted);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.