简体   繁体   English

通用方法的数组参数的Java类型推断

[英]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)'. 我收到错误信息“方法contains(T [],T)不适用于参数(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 . 实际上,这里发生的是将int常量1 “装箱”到Integer.valueOf(1) ,该对象是Integer类型的对象。

You can pass also an int[] to a generic method, because int[] is an object type itself. 您还可以将int[]传递给泛型方法,因为int[]本身就是对象类型。 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. 但是,不能将这两个变量与相同的类型变量混合使用: int[]Integer不是相关类型,因此,没有两个参数都满足的单个类型变量T There is no equivalent auto-boxing operator from int[] to Integer[] . int[]Integer[]没有等效的自动装箱运算符。

As such, you would need to pass an Integer[] array as the first parameter: 因此,您需要将Integer[]数组作为第一个参数传递:

method(new Integer[1], 0);

why use primitive type here. 为什么在这里使用primitive类型。 Generics only work with referenced type. 泛型仅适用于referenced类型。

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

better to go with 最好和

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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