gpt4 book ai didi

Java 8 Streams,未编译的示例

转载 作者:行者123 更新时间:2023-12-01 21:59:26 25 4
gpt4 key购买 nike

我的问题很短,为什么它不能编译?

final ArrayList <Integer> list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());

问题出现在 Collectors.toList()部分。

最佳答案

Collectors.toList() 返回一些 List 实现,该实现不一定是 ArrayList,而且可能不是。

尝试

final List <Integer> list = IntStream.rangeClosed(1, 20)
.boxed()
.collect(Collectors.toList());

如果您特别需要 ArrayList,可以使用 collect(Collectors.toCollection(ArrayList::new))

final ArrayList <Integer> list = IntStream.rangeClosed(1, 20)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));

关于Java 8 Streams,未编译的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823224/

25 4 0