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