-2

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)
Community
  • 1
  • 1
redMist
  • 179
  • 11
  • you need to copy your source array in merge sort anyways :) – Sleiman Jneidi Dec 27 '15 at 22:35
  • and by the way, your merge sort is broken http://googleresearch.blogspot.co.uk/2006/06/extra-extra-read-all-about-it-nearly.html – Sleiman Jneidi Dec 27 '15 at 22:35
  • @Sleiman Thank for pointing out bug. As for copying, yes here i need to copy array anyway, but this is where i started thinking about how to create generic array. Maybe better question would be if way around like this 'this.tmp=(T[]) Arrays.copyOf(new Object[]{}, n);' would be very bad solution and why. – redMist Dec 27 '15 at 23:00
  • 1
    In Java, every array has a public `clone()` method. You could simply write `this.tmp = list.clone();`. – VGR Jan 02 '16 at 03:25

1 Answers1

2

You can use this method from guava

  static <T> T[] newArray(T[] reference, int length) {
    Class<?> type = reference.getClass().getComponentType();
    @SuppressWarnings("unchecked")
    T[] result = (T[]) Array.newInstance(type, length);
    return result;
  }
v.ladynev
  • 16,591
  • 5
  • 37
  • 56
  • I'll use this method as it seems a preferable solution, but I can't mark it as answer, thanks though. – redMist Dec 27 '15 at 22:59