Why do the new Java 8 streams return an Object Array on toArray calls? -
whilst working on project involving java 8's new streams, noticed when called stream#toarray()
on stream, homecoming object[]
instead of t[]
. surprised was, started digging source code of java 8 , couldn't find reason why didn't implement object[] toarray();
t[] toarray();
. there reasoning behind this, or (in)consistency?
edit 1: noticed in answers lot of people said not possible, code snippet compiles , homecoming expected result?
import java.util.arrays; public class test<r> { private object[] items; public test(r[] items) { this.items = items; } public r[] toarray() { homecoming (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())); } }
this same problem list#toarray()
has. type erasure prevents knowing type of array should return. consider following
class custom<t> { private t t; public custom (t t) {this.t = t;} public t[] toarray() {return (t[]) new object[] {t};} // if not object[], type? } custom<string> custom = new custom("hey"); string[] arr = custom.toarray(); // fails
an object[]
not string[]
, hence cannot assigned one, regardless of cast. same thought applies stream
, list
. utilize overloaded toarray(..)
method.
java java-8
No comments:
Post a Comment