0

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[])
4
  • No sorry that was just a code-typo. I am trying to call insertionSort on temp which should manipulate the array passed to it. Commented Nov 4, 2015 at 21:40
  • 3
    Well then, what is the problem? Compilation error? Please include the exact error text and where it appears in the code by editing your question. Runtime error? Include the error and stack trace. Incorrect output? Include a sample input and the desired and undesired output. Most of all, don't give single lines of code out of context, but instead, create a minimal reproducible example. Commented Nov 4, 2015 at 21:45
  • Compile time. Added it to the question. Commented Nov 4, 2015 at 21:47
  • I actually figured out the issue. I was mistakenly declaring InsertionSort with a different type than a generic type! Commented Nov 4, 2015 at 21:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.