问题
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);
...but this does not:
Arrays.asList(scores).stream()
.forEach(System.out::println);
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.
回答1:
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
.
If you change scores
to Integer[]
, you'll get the output you expect (i.e. Arrays.asList(scores)
will return a List<Integer>
).
回答2:
The reason the second code snippet does not work is that there is no such thing as List<int>
in Java. That is why Arrays.asList(scores)
does not produce what you expect.
Switching from int[]
to Integer[]
would fix this problem, in the sense that the two pieces of code would produce identical results. However, your code would be less efficient, because all int
s would be boxed.
In fact, efficiency is the reason behind having overloads of stream
for primitive arrays. Your call Arrays.stream(scores)
is routed to stream(int[] array)
, producing IntStream
object. Now you can apply .forEach(System.out::println)
, which calls println(int)
, again avoiding boxing.
回答3:
Arrays.asList expects arrays of Object not arrays of primitives. It does not complain on compile time because arrays of primitive is an object.
It can take one object as list but what is inside that object(arrays of primitive is an object) cannot be convert to list.
Arrays of primitive can be convert to stream using
IntStream
,DoubleStream
and LongStream
like this
double[] doubleArray = {1.1,1.2,1.3};
DoubleStream.of(doubleArray).forEach(System.out::println);
int[] intArray = {1,2,3,4,5,6};
IntStream.of(intArray).forEach(System.out::println);
long[] longArray = {1L,2L,3L};
LongStream.of(longArray).forEach(System.out::println);
来源:https://stackoverflow.com/questions/37252468/arrays-streamarray-vs-arrays-aslistarray-stream