I am trying to instantiate an array by using lambda expressions.
the code I am trying to use is:
public class Main {
static int x = 0;
public static void main(String[] args) {
Test[] t = (Test[]) Stream
.generate(() -> new Test(x++, 0))
.limit(10)
.map((Test v) -> {
v.a = v.a * 2;
return v;
})
);
the class I am trying to instantiate is called Test:
public class Test {
int a, b;
Test(int a, int b) {
this.a = a;
this.b = b;
}
}
I can not perform the cast, it raises an exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lperson.Test; at person.Main.main(Main.java:37) Java returned: 1
But if you look at the object classes:
The array is a "[Ljava.lang.Object;" instance
//class "[Ljava.lang.Object;"
System.out.println(
Stream.generate(() -> new Test(x++, 0))
.limit(10)
.map((Test v) -> {
v.a = v.a * 2;
return v;
})
.toArray().getClass()
);
Each object of the array is a "Test" instance
//class "Test"
System.out.println(
Stream.generate(() -> new Test(x++, 0))
.limit(10)
.map((Test v) -> {
v.a = v.a * 2;
return v;
})
.toArray()[0].getClass()
);