6

Was just getting my hands dirty with Java 8 and stumbled on a behaviour as below -

public static void main(String... args){
    System.out.println("[Start]");
    int[] ints = {1, 2, 3, 4};
    Stream.of(ints).forEach(i->System.out.println("Int : "+i));


    Integer[] integerNums = {1, 2, 3, 4};
    Stream.of(integerNums).forEach(i->System.out.println("Integer : "+i));

    System.out.println("[End]");
}

And the output is :

[Start]
Int : [I@5acf9800
Integer : 1
Integer : 2
Integer : 3
Integer : 4
[End]

Whereas I was expecting the code to print all int's and Integer's in both the cases? Any insights on this would be greatly helpful...

1 Answer 1

15

Generics don't work with primitive types. The Stream.of method is declared as

static <T> Stream<T> of(T... values)

When you use

Stream.of(ints)

where ints is an int[], Java doesn't see a number of int elements (primitive types), it sees a single int[] element (which is a reference type). So the single int[] is bound as the only element in the array represented by T... values.

So values becomes an int[][] and each of its elements is an int[], which print like

[I@5acf9800
Sign up to request clarification or add additional context in comments.

1 Comment

You can use IntStream.of for ints.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.