我正在开发我的第一个使用通用方法的程序。我认为我通过将参数设置为正确地做到了这一点,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
Run Code Online (Sandbox Code Playgroud)
也许你可以帮我。如果是这样,我将不胜感激。
int泛型不能与原始类型(如或 )一起使用double,它们不是对象或类。您将必须使用盒装版本Integer[]和Double[].
特别是,如果您想支持接受原语int[]和double[]数组,则必须编写两次代码。=((我可以想到一种半解决方法,但不能不使用外部库......)
| 归档时间: |
|
| 查看次数: |
3381 次 |
| 最近记录: |