简体   繁体   中英

Java: generic type array as function parameter

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM