Arrays.stream(array)vs Arrays.asList(array).stream() [英] Arrays.stream(array) vs Arrays.asList(array).stream()
问题描述
在这个问题中,已经回答过两个表达式都相等,但在这种情况下,它们会产生不同的结果。对于给定的 int []得分
,为什么这样做:
In this question it has already been answered that both expressions are equal, but in this case they produce different results. For a given int[] scores
, why does this work:
Arrays.stream(scores)
.forEach(System.out::println);
...但这不是:
Arrays.asList(scores).stream()
.forEach(System.out::println);
据我所知 .stream()
可以在任何Collection上调用,列表肯定是。第二个代码片段只返回一个包含整个数组而不是元素的流。
As far as I know .stream()
can be called on any Collection, which Lists definitely are. The second code snippet just returns a stream containing the array as a whole instead of the elements.
推荐答案
你看到的行为不是特定于 Stream
s。
Arrays.asList(得分)
在传递给它时返回 List< int []>
一个 int []
,因为泛型类型参数不能被基本类型替换。因此,当您调用 asList(T ... a)
时,编译器使用 int []
代替 T
。
The behavior you see is not specific to Stream
s.
Arrays.asList(scores)
returns a List<int[]>
when you pass to it an int[]
, since a generic type parameter can't be replaced by a primitive type. Therefore, when you call asList(T... a)
, the compiler uses int[]
in place of T
.
如果您将得分
更改为整数[]
,你会得到你期望的输出(即 Arrays.asList(得分)
将返回列表<整数>
) 。
If you change scores
to Integer[]
, you'll get the output you expect (i.e. Arrays.asList(scores)
will return a List<Integer>
).
这篇关于Arrays.stream(array)vs Arrays.asList(array).stream()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!