recently I was watching an algorithm course where the teacher used cPP"s template and function pointers to complete an implementation, so I tried to use java to do it through reflection and generics, but there was a problem.
I want to dynamically test various sort functions in SortClass through java reflection and generics, so I don"t know how to solve the parameters of the getmethod method and the invoke method. The implementation I wrote keeps reporting parameter exceptions
Code
class SortClass<T extends Comparable>{
//
public void selectSort(T[] a){
for(int i = 0; i < a.length; iPP){
int min = i;
for(int j = i+1; j < a.length; jPP){
if(a[j].compareTo(a[min]) < 1){
swap(a,j,min);
}
}
}
}
//
public void swap(T[] arr, int a, int b){
T temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
//
public void testSort(String sortName,Object[] a){
long startTime = System.currentTimeMillis();
try {
Method method = this.getClass().getMethod(sortName,Object[].class);
method.invoke(this,a);
} catch (NoSuchMethodException e) {
System.out.println(e.getMessage()+" not find");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println(sortName + "use time:" + (endTime-startTime));
}
}
I hope there are some improved methods or code to complete this implementation.