Arrays.stream(array) vs Arrays.asList(array).stream() [英] Arrays.stream(array) vs Arrays.asList(array).stream()

查看:39
本文介绍了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() 可以在任何集合上调用,列表肯定是.第二个代码片段只返回一个包含整个数组而不是元素的流.

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.Arrays.asList(scores) 当你传递给它一个 int[] 时返回一个 List,因为一个泛型类型参数不能被原始类型替换.因此,当您调用 asList(T... a) 时,编译器使用 int[] 代替 T.

The behavior you see is not specific to Streams. 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.

如果您将 scores 更改为 Integer[],您将得到您期望的输出(即 Arrays.asList(scores)返回一个 List).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆