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[]?

2
  • Use an IntStream. IntStream.of(ints).forEach(a -> System.out.println(a)); Commented Jun 21, 2016 at 2:23
  • 1
    or .forEach(System.out::println) Commented Jun 21, 2016 at 2:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.