使用Java列表时遇到编译错误,toArray(),[重复]

4smxwvx5  于 2022-12-25  发布在  Java
关注(0)|答案(1)|浏览(303)
    • 此问题在此处已有答案**:

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[])

希望获取转换后的数组,但失败。

oknwwptz

oknwwptz1#

泛型类型不匹配,因为List属于Integer。您可以创建Integer[]或使用流转换为int[]

int[] arr = temp.stream().mapToInt(i -> i).toArray();

相关问题