Java 不兼容的类型:推理变量 T 有不兼容的边界
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27522741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
incompatible types: inference variable T has incompatible bounds
提问by PDStat
I have the following piece of code
我有以下代码
public int solution(int X, int[] A) {
List<Integer> list = Arrays.asList(A);
For some reason it's throwing the following compilation error
出于某种原因,它抛出以下编译错误
Solution.java:11: error: incompatible types: inference variable T has incompatible bounds List list = Arrays.asList(A); ^ equality constraints: Integer lower bounds: int[] where T is a type-variable: T extends Object declared in method asList(T...)
Solution.java:11: error: incompatible types: inference variable T has incompatible bounds List list = Arrays.asList(A); ^ 等式约束:整数下界:int[] 其中 T 是类型变量:T extends Object 在方法 asList(T...) 中声明
I assume this a Java 8 feature, but I'm not sure how to resolve the error
我认为这是 Java 8 功能,但我不确定如何解决该错误
采纳答案by tobias_k
Arrays.asList
is expecting a variable number of Object
. int
is not an Object
, but int[]
is, thus Arrays.asList(A)
will create a List<int[]>
with just one element.
Arrays.asList
期待可变数量的Object
。int
不是 an Object
,而是int[]
is,因此Arrays.asList(A)
将创建一个List<int[]>
只有一个元素的 a 。
You can use IntStream.of(A).boxed().collect(Collectors.toList());
您可以使用 IntStream.of(A).boxed().collect(Collectors.toList());
回答by Sagar Koshti
There is no shortcut for converting from int[] to List as Arrays.asList does not deal with boxing and will just create a List which is not what you want. You have to make a utility method.
从 int[] 转换为 List 没有捷径,因为 Arrays.asList 不处理装箱,只会创建一个不是您想要的 List。你必须制定一个实用方法。
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
intList.add(ints[index]);
}
回答by Peter Lawrey
In Java 8 you can do
在 Java 8 中你可以做
List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());