Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection.toArray(IntFunction<T[]> generator) does not receive the collection size

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];
    }
}
like image 362
zeugor Avatar asked Oct 29 '25 03:10

zeugor


1 Answers

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);
like image 86
Naman Avatar answered Oct 30 '25 17:10

Naman