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()));
}
}