gpt4 book ai didi

java8 流 api 抛出不兼容的类型 : Object[] cannot be converted to Integer[] when converting String array to Integer array

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:20 24 4
gpt4 key购买 nike

我的以下代码:

String[] valStrs=data.split(";");//data is a string
Integer[] vals=Arrays.stream(valStrs).map(Integer::valueOf).toArray();

正在 throw :

error: incompatible types: Object[] cannot be converted to Integer[] [in Codec.java]
Integer[] vals=Arrays.stream(valStrs).map(Integer::valueOf).toArray();

我想我正在尝试获得 String流,然后映射 String进入Integer通过 Integer::valueOf ,并收集这些 Integer成一个数组。

那么为什么会出现这个错误呢?快速搜索但找不到答案。


更新:

事实上int[] arr= Arrays.stream(valStrs).mapToInt(Integer::parseInt).toArray();完美运行。

最佳答案

您必须将对整数数组的构造函数引用传递给 toArray像这样。否则它将创建一个 Object[]默认情况下。

Arrays.stream(valStrs).map(Integer::valueOf).toArray(Integer[]::new);

mapToInt创建一个 IntStream , 它是 toArray()函数返回 int[] .这是声明。

int[] toArray();

相反,map(Integer::valueOf)创建一个 Stream<Integer>它是 toArray返回 Object[]除非另有规定。这是实现。

@Override
public final Object[] toArray() {
return toArray(Object[]::new);
}

调用 toArray(Integer[]::new)将调用此重载方法。

public final <A> A[] toArray(IntFunction<A[]> generator)

这是文档的摘录。

Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array.

generator a function which produces a new array of the desired type and the provided length

关于java8 流 api 抛出不兼容的类型 : Object[] cannot be converted to Integer[] when converting String array to Integer array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54789016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com