1

I have some Java 8 code like the following snippet.

public class Test {
  static protected <T extends Comparable<T>> T[] myFunction(T[] arr) {
    // do stuff...
    return arr;
  }

  public static void main(String[] args) {
    int[] a = new int[] {1,4,25,2,5,16};
    System.out.println(Arrays.toString(myFunction(a)));
  }
}

When I try to run it, I get the error below:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method myFunction(T[]) in the type LottoResult is not applicable for the arguments (int[])

Why does this happen and how do I have to rewrite it to be able to also pass int[] arrays to myFunction?

1
  • 1
    int[] is primitive and T[] expects non-primitive types Commented Jan 11, 2016 at 13:34

1 Answer 1

9

An array T[] implies that the array is of some-reference type T, while you're passing an array of primitives (int[]). This is why you get the compilation error.

In order to get it working, you need to do:

Integer[] a = new Integer[] {1,4,25,2,5,16};

This will create an array of a reference type (Integer[]), because auto-boxing would have taken place.

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.