While I was working on a project using the new Java 8 threads, I noticed that when I called Stream#toArray() on the stream, it returns Object[] instead of T[] . Surprised, like me, I started digging into the Java 8 source code and could not find the reasons why they did not implement Object[] toArray(); like T[] toArray(); . Are there any considerations behind this, or is it just (in) consistency?
EDIT 1: I noticed in the answers that many said it would not be possible, but this piece of code compiles and returns 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())); } }
java java-8
Martijn
source share