0
我的問題很簡短,爲什麼不編譯?Java 8 Streams,不能編譯的例子
final ArrayList <Integer> list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
問題發生在Collectors.toList()
部分。
我的問題很簡短,爲什麼不編譯?Java 8 Streams,不能編譯的例子
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());
您可以使用collect(Collectors.toCollection(ArrayList::new))
如果你特別需要一個ArrayList
。
final ArrayList <Integer> list = IntStream.rangeClosed(1, 20)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
謝謝!而已 :) – azalut
爲什麼聲明爲ArrayList?如果你真的不需要它,那麼聲明接口而不是實現是個好習慣。 – saroff
我在網上找到了這個例子,想知道爲什麼 – azalut