Saturday, 28 September 2013

Why Stream.toArray method doesn't return a generic array?

Why Stream.toArray method doesn't return a generic array?

I am working with Java-8 streams, and I've this code from coreservlets
tutorial where it is filtering an Integer[] to get all even numbers:
Integer[] ints = { 1, 2, 3, 4, 5, 6 };
Integer[] evens = (Integer[])Stream.of(ints).filter(n -> n % 2 ==
0).toArray();
Then I realised that the Stream#toArray() method returns an Object[], thus
resulting in ClassCastException at runtime, as expected. But why is that?
Why doesn't Stream interface directly provide a T[] toArray() method,
which would return a T[] for the appropriate Stream<T> instantiation?
There is one more method - <A> A[] toArray(IntFunction<A[]>), but I'm not
able to understand the usage of that method at all. Clearly the type
parameter is different from the one in Stream<T>. I tried to use it like
this:
Integer[] evens = Stream.of(ints).filter(n -> n % 2 ==
0).toArray(Integer[]::new);
but it isn't working. It shows the following compiler error on
Integer[]::new:
Error Message: Constructed array Integer[] cannot be assigned to A[] as
required in the interface descriptor
So, how exactly do we use that method? And how exactly should I achieve
what I've explained above? How to get result of toArray() properly
converted to Integer[], without any warning?

No comments:

Post a Comment