0
我正在處理我的第一個使用泛型方法的程序。我認爲我是通過將參數設置爲selectionSort(T[] a)
來正確地做到這一點,以便該方法可以接收任何對象的數組。通用方法 - 不能應用於給定類型
public class SelectionSort {
protected int[] arrayOne = {1,2,3,4,5,6,7,8};
protected double[] arrayTwo = {1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0};
public static <T extends Comparable<T>> void selectionSort(T[] a)
{
for (int index =0; index < a.length; index++)
{
int minElementIndex = index;
T minElementValue = a[index];
for (int i = index + 1; i < a.length; i++)
{
if (a[i].compareTo(minElementValue) < 0)
{
minElementIndex = i;
minElementValue = a[i];
}
}//end of inner for loop
a[minElementIndex] = a[index];
a[index] = minElementValue;
}//end of outer for loop
for(int indexb = 0; indexb<a.length; indexb++)
{
System.out.printf("%d ", a[indexb]);
if(indexb == a.length)
System.out.println("");
}
}
public static void main(String[] args)
{
selectionSort(arrayOne);
selectionSort(arrayTwo);
}}//end of main and SelectionSort
也許你可以幫我一把。如果是這樣,我將不勝感激。
我將變量更改爲Integer []和Double []而不是int [] double [],但它仍然 – 2012-04-20 16:46:26
究竟是什麼錯誤給你?(重新讀你的代碼,我懷疑你需要使'arrayOne'和'arrayTwo'靜態...) – 2012-04-20 17:06:04
工作,將它們改變爲靜態。 – 2012-04-20 17:17:18