(这可能与https://stackoverflow.com/a/30312177/160137有关,但恐怕我还是不明白,所以我这样问我的问题,希望能够得出一个我可以更容易理解的答案。 )为什么Collectors.toList()不在原始集合上工作?
通常,当我有一个流,我可以将其转换为使用在收藏家类的静态方法一个集合:
List<String> strings = Stream.of("this", "is", "a", "list", "of", "strings")
.collect(Collectors.toList());
类似的过程不会在原始流然而工作,如其他人已经注意到:
IntStream.of(3, 1, 4, 1, 5, 9)
.collect(Collectors.toList()); // doesn't compile
我能做到这一点,而不是:
IntStream.of(3, 1, 4, 1, 5, 9)
.boxed()
.collect(Collectors.toList());
或者我可以这样做:
IntStream.of(3, 1, 4, 1, 5, 9)
.collect(ArrayList<Integer>::new, ArrayList::add, ArrayList::addAll);
的问题是,为什么不Collectors.toList()只是做,对于原始流?是否无法指定包装类型?如果是这样,为什么这不工作:
IntStream.of(3, 1, 4, 1, 5, 9)
.collect(Collectors.toCollection(ArrayList<Integer>::new)); // nope
任何洞察力将不胜感激。
因为(即使在Java-8中),也没有“List”。原始类型**不是**'对象'。 –
签名中的泛型根本不适用于原始类型。这样简单。 – Dici
明确调用'boxed()'和允许原始流上的盒装收集器之间没有功能差异。如果你问为什么不允许方便,也许设计师想让拳击很容易看出来。 – shmosel