Whilst I was working on a project involving Java 8's new streams, I noticed that when I called Stream#toArray() on a stream, it return an Object[] instead of a T[]. Surprised as I was, I started digging into the source code of Java 8 and couldn't find any reason why they didn't implement Object[] toArray(); as T[] toArray();. Is there any reasoning behind this, or is it just an (in)consistency?
EDIT 1: I noticed in the answers that a lot of people said this would not be possible, but this code snippet compiles and return the expected result?
import java.util.Arrays;
public class Test<R> {
private Object[] items;
public Test(R[] items) {
this.items = items;
}
public R[] toArray() {
return (R[]) items;
}
public static void main(String[] args) {
Test<Integer> integerTest = new Test<>(new Integer[]{
1, 2, 3, 4
});
System.out.println(Arrays.toString(integerTest.toArray()));
}
}
R? If you want specific types to be returned, pass a generator to the method. For example for a String array, do the following:streamString.toArray(String[]::new)Object[]is not necessarily aR[]. That cast is bound to fail at runtime.R, so this will throw aRuntimeExceptionR[]should be your warning sign. This is an unchecked cast, and the compiler tells you so (but you probably just ignored this).items[]is not an array ofR[], so the compiler is quite right to say that it can't verify this cast -- and it can't stop a client from casting the returned array toObject[], and then putting non-R values in it, which would subvert the supposed type-safety of saying "this is an array of R".