I got Cannot create a generic array of T
while trying to create generic array
like this
tmp = new T[n];
I found this topic but having to pass class every time i want to call method seemed to much trouble to me.
So i solved it in next way
this.tmp=Arrays.copyOf(list, n);
Is it good solution considering 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];
}
}
}
Edit: Maybe better question would be; what if I used folowing line of code instead?
this.tmp=(T[]) Arrays.copyOf(new Object[]{}, n)