1

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?

nimo23
  • 5,170
  • 10
  • 46
  • 75

1 Answers1

2

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));
}
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Interesting. So I conclude that `CompletableFuture[]::new` is exactly the same as `new CompletableFuture[0])`? Because the first also accepts an `IntFunction`. Correct me if I am wrong. – nimo23 Feb 19 '21 at 20:47
  • 1
    @nimo23 no it isn't. that `CompletableFuture[]::new` is actually `x -> new CompletableFuture[x]`... – Eugene Feb 19 '21 at 20:48
  • Oh, yes that's a lambda. So I will stick with version 1 or 2. Thanks! – nimo23 Feb 19 '21 at 20:50