Lambda表达式不会迭代int []

时间:2016-06-21 02:17:13

标签: java lambda

在Java 8中练习lambda表达式时,我发现forEach不会遍历int []的所有元素。例如,

int[] ints = new int[5];
Arrays.asList(ints).forEach(a -> System.out.println(a));

输出是:

[I@573fd745  // this is also what I get if print the array directly in console

如果像这样初始化数组并不重要。

int[] ints2 = {1,2,3,4,5};
Arrays.asList(ints2).forEach(a -> System.out.println(a));

输出是:

[I@4f2410ac

但如果我使用简单的for循环,我会得到正确的结果

int[] ints = new int[5];
for (int i = 0; i < ints.length; i++) {
    System.out.println(ints[i]);
}

输出

0
0
0
0
0

同样,两个lambdas都适用于Integer []&amp;串[]

Integer[] integers = new Integer[5];
Arrays.asList(integers).forEach(a -> System.out.println(a));

输出

null   // similarly for String[]
null
null
null
null

任何人都可以了解这里发生的事情吗?为什么forEach循环遍历Integer []的元素,但是通过int []?

0 个答案:

没有答案