[英]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.