David Marciel David Marciel - 7 months ago 27
Java Question

initialize an array by using casted lambda expressions

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

Answer

You can't just cast a stream and expect it to become an array.

Use the A[] toArray(IntFunction generator) method.

    Test[] a = Stream.generate(() -> new Test(x++, 0))
            .limit(10)
            .map((Test v) -> {
                v.a = v.a * 2;
                return v;
            })
            .toArray(Test[]::new);
Comments