I think that in general it is O(n)
, since the declared array need to be zeroes with default values, in your case with false
.
But a VM can also prove that this array is not read immediately, that is someone first writes all the elements to it and only after that, reads them. In such a condition the complexity would be O(1)
, because you are not really doing anything (no default values are placed inside the array itself) - thus constant.
This, for example, is what happens in java-11
with Collection::toArray
sort of, via :
default <T> T[] toArray(IntFunction<T[]> generator) {
return toArray(generator.apply(0));
}
So when you have something like:
List.of(1, 2, 3, 4)
.toArray(x -> new Integer[x]);
The implementation will actually do new Integer[0]
and use that coupled with some System.arrayCopy
, instead of the inferred new Integer[4]
. This is done because the VM can prove that zeroing is not needed, thus skip it entirely.