简体   繁体   中英

Java - type inference for array paramater of a generic method

Type inference doesn't seem to work for arrays with generic methods? I receive the error 'The method contains(T[], T) is not applicable for the arguments (int[], int)'. How should I be doing this?

method(new int[1], 0); //Error

...

public static <T> void method(T[] array, T value) {
    //Implement
}

您可以使用Integer而不是int,因为泛型不适用于基本类型。

Generics doesn't work with primitive types, only with object types.

You can do what looks like using generics with primitive types, due to auto-boxing:

<T> void methodOne(T value) {}

methodOne(1);  // Compiles OK, T = Integer.

What is actually happening here is that the int literal 1 is being "boxed" to Integer.valueOf(1) , which is an object of type Integer .

You can pass also an int[] to a generic method, because int[] is an object type itself. So:

methodOne(new int[1]);  // Compiles OK, T = int[].

However, you can't mix these two with the same type variable: int[] and Integer are not related types, so there is no single type variable T which is satisfied by both parameters. There is no equivalent auto-boxing operator from int[] to Integer[] .

As such, you would need to pass an Integer[] array as the first parameter:

method(new Integer[1], 0);

why use primitive type here. Generics only work with referenced type.

method(new int[1], 0); //Error

better to go with

 method(new Integer[]{1,2,3,4}, 0); //works fine

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