我的以下代码:
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/