I am working on my first program that utilizes a generic method. I thought I was doing it correctly by setting the parameter to selectionSort(T[] a) so the method could receive an array of any object.
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
Perhaps you can help me out. If so I would greatly appreciate it.
Generics cannot be used with primitive types like
intordouble, which are not objects or classes. You will have to use the boxed versionsInteger[]andDouble[].In particular, if you want to support accepting primitive
int[]anddouble[]arrays, you will have to write the code twice. =( (I can think of one semi-workaround, but not without using external libraries…)