toArray by lambda, fixed size list or empty constructor

Viewed 69

I read the previous post .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])? and want to know if this is still valid with >jdk9:

version 1 (according to previous post, the fastest):

futures.toArray(new CompletableFuture<?>[0]))

version 2 (is the same as version 1):

futures.toArray(new CompletableFuture[0]))

version 3 (uses lambda expression and it's static access is known to be fast):

futures.toArray(CompletableFuture[]::new)

and version 4 (which is slowest according to the previous post):

futures.toArray(new CompletableFuture[futures.size()])

Or is there no difference between those versions today?

1 Answers

It is valid everywhere, and the all mighty Shipilev has made it clear a while ago.

There is a reason List::toArray has a default method since jdk-11 that looks like this:

 default <T> T[] toArray(IntFunction<T[]> generator) {
    return toArray(generator.apply(0));
}
Related