- 此问题在此处已有答案**:
How can I convert List to int[] in Java? [duplicate](16个答案)
(19个答案)
昨天关门了。
我想用list.toArray()把列表转换成数组,这样代码就简单了。但是In遇到了如下的"编译错误"。有人能解释一下原因吗?谢谢!
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
List<Integer> temp = new ArrayList<>();
for(int num1:nums1) set.add(num1);
for(int num2:nums2) {
if(!set.contains(num2)) continue;
temp.add(num2);
set.remove(num2);
}
int[] re = temp.toArray(new int[temp.size()]);
return re;
}
Line 11: error: no suitable method found for toArray(int[])
int[] re = temp.toArray(new int[temp.size()]);
^
method Collection.<T#1>toArray(IntFunction<T#1[]>) is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; int[] cannot be converted to IntFunction<T#1[]>))
method List.<T#2>toArray(T#2[]) is not applicable
(inference variable T#2 has incompatible bounds
equality constraints: int
lower bounds: Object)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1>toArray(IntFunction<T#1[]>)
T#2 extends Object declared in method <T#2>toArray(T#2[])
希望获取转换后的数组,但失败。
1条答案
按热度按时间oknwwptz1#
泛型类型不匹配,因为
List
属于Integer
。您可以创建Integer[]
或使用流转换为int[]
。