Why generateEmptyArrayBySize method is receiving 0 as input, instead of 3?
I was expecting to receive the list size.
public class CollectionToArrayTest {
    public static void main(String[] args) {
        var list = List.of(1, 2, 3);
        var array = list.toArray(CollectionToArrayTest::generateArrayBySize);
        out.println("array: " + Arrays.toString(array)); // array: [1, 2, 3]
    }
    private static Integer[] generateArrayBySize(int arraySize) {
        out.println("arraySize: " + arraySize); // arraySize: 0
        return new Integer[arraySize];
    }
}
If you look at the implementation of the Collection.toArray method you'll see:
return toArray(generator.apply(0));
On the other side, the implementation of the IntFunction that you have looks similar to:
new IntFunction<Integer[]>() {
    @Override
    public Integer[] apply(int arraySize) { // check the parameter here
        return generateArrayBySize(arraySize);
    }
}
So the value passed on to the generateArrayBySize is the same as that passed to the apply method of the IntFunction, i.e. 0. Ofcourse, a straight forward way to transform the list into an array would be:
var array = list.toArray(Integer[]::new);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With