I'm trying to use ArrayList's built in Java method that converts an ArrayList to an array. However, the issue is that Java converts the array to an array of type objects. I am trying to convert this to an array of type T (generic type). I tried passing in the class type into the constructor of the class using it to cast the array, but I had no luck. My code is below. Any help would be appreciated:
public class QuickSelect<T extends Comparable<T>> extends Sort<T> implements Selection<T> {
Class<T> t; // for class type
QuickSelect(Class<T> t){
this.t = t;
}
@Override
public T select(T[] data, int n, int k) {
if(data.length == 0) return null;
if(k == 1) return data[0];
if(k >= n || k <=0 ) return null;
Random randomGenerator = new Random();
int pivotPosition = randomGenerator.nextInt(n-1);
T pivotValue = data[pivotPosition];
ArrayList<T> lessThanPivot = new ArrayList<T>();
ArrayList<T> equalToPivot = new ArrayList<T>();
ArrayList<T> greatThanPivot = new ArrayList<T>();
for(int i=0; i < n; i++){
if(compare(pivotValue, data[i]) < 0) lessThanPivot.add(data[i]);
else if(compare(pivotValue, data[i]) == 0) equalToPivot.add(data[i]);
else greatThanPivot.add(data[i]);
}
Class<?> tClass = t.getClass();
if(k <= lessThanPivot.size()) select(lessThanPivot.toArray(), lessThanPivot.size(), k); // this part of the code is where the issue is
return null; //don't worry about this for now
}
}