Hadi
Hadi

Reputation: 995

Pass array of generics to a method that takes array of generic

I have a Java method that takes as input, a generic array:

void insertionSort(T[] data) {

 T sortValuePointer;

   for (int i = 1; i < data.length; i++) {

       sortValuePointer = data[i];

        int j = i;

        while (j > 0 && compare(sortValuePointer,data[j - 1]) < 0) {

            data[j] = data[j - 1];

            j--;
        }

        data[j] = sortValuePointer;

    }

}

And I have a an array that was created as the following:

   T[]  temp=  (T[]) Array.newInstance(t, 5);

Where Class t is taken as input:

   Class<T> t;

And the method insertionSort is in the InsertionSort class. So I am not able to make a call like the following:

 insertionSort.insertionSort(temp);

I get the following compile-time error: Exception in thread "main" java.lang.Error: Unresolved compilation problem:

The method insertionSort(Integer[]) in the type InsertionSort<Integer> is not applicable for the arguments (T[])

Upvotes: 0

Views: 109

Answers (1)

Hadi
Hadi

Reputation: 995

I fixed the issue. The issue was that I was creating the parent class using a particular type! In my case, this was:

InsertionSort<Integer> insertionSort = new InsertionSort<Integer>();

Whereas it should've been:

InsertionSort<T> insertionSort = new InsertionSort<T>();

And that solved it.

Upvotes: 1

Related Questions