0

While practicing lambda expressions in Java 8 I found that forEach does not loop through all elements of int[]. For e.g.

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

Output is :

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

It does not matter if array is initialized like this.

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

Output is:

[I@4f2410ac

But if I use simple for loop, I get correct results

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

Output is

0
0
0
0
0

Also both lambdas work fine for Integer[] & String[]

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

Output is

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

Can anyone shed some light on what is happening over here? Why forEach loops through elements of Integer[] but through int[]?

Master Chief
  • 2,520
  • 19
  • 28

0 Answers0