I got "Cannot create a generic array of T" while trying to create a generic array like this
tmp = new T[n];
I found [this][1] [1]: https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java, but having to pass class every time I want to call method seemed too much trouble to me.
So I solved it in the next way
this.tmp=Arrays.copyOf(list, n);
Is this a good solution considering the rest of code? Why yes? Why no?
Full code:
public class MergeSort<T extends Comparable<? super T>>{
private T[] A;
private T[] tmp;
private int n;
public void sort(T[] list){
this.A=list;
this.n=list.length;
this.tmp=Arrays.copyOf(list, n);
mergeSort(0,n-1);
}
private void mergeSort(int low,int high){
if(low<high){
int middle=(low+high)/2;
mergeSort(low, middle);
mergeSort(middle+1, high);
merge(low,middle,high);
}
}
private void merge(int left,int right,int rightEnd){
int leftEnd=right,k=left;
right++;
while(left<=leftEnd && right<=rightEnd){
if(A[left].compareTo(A[right])<=0)
tmp[k++]=A[left++];
else
tmp[k++]=A[right++];
}
while(left<=leftEnd)
tmp[k++]=A[left++];
while(right<=rightEnd)
tmp[k++]=A[right++];
for (int i = 0; i <= rightEnd; i++) {
A[i] = tmp[i];
}
}
}
Maybe a better question would be; what if I used following line of code instead?
this.tmp=(T[]) Arrays.copyOf(new Object[]{}, n)