Consider the following code fragment
String strings[] = {"test"};
final List<String> collect = java.util.Arrays.stream(strings).collect(java.util.stream.Collectors.toList());
final Double[] array = java.util.Arrays.stream(strings).toArray(Double[]::new);
Why can Java guarantee the correct type in the collect-case (changing the generic type of collect to e.g. Double leads to a compile time error), but not in the array case (compiles fine, despite apply(int)
of Double[]::new
gives a Double[]
, not an Object[]
, but throws ArrayStoreException
if used incorrectly as above)?
What would be the best way to generate a compile time error in case I change the type of the stream without changing the given IntFunction
in the toArray
call?