JDK-8060192 : Add default method A[] Collection.toArray(IntFunction generator)
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P3
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2014-10-13
  • Updated: 2018-07-09
  • Resolved: 2018-06-21
JDK 11 JDK 12
11 b20Fixed 12Fixed
Related Reports
CSR :  
Relates :  
Relates :  
Relates :  
Sub Tasks
JDK-8206941 :  
Description
There exists a method on j.u.Stream that makes it a little easier to create an array of an appropriate type (at the expense of throwing a ArrayStoreException if the array component type is not a super type of all elements in the stream):

    <A> A[] toArray(IntFunction<A[]> generator);

An equivalent method can also be added to Collection.

Given the existence of:

  Collection.toArray(T[] a)

this does introduce a source code incompatibility for code passing nulls:

  toArray(null);

although this is only likely to occur in tests (such as the TCK perhaps).
Comments
There is source incompatibility with this change so I think we should add a release note.
09-07-2018

Subsequent review thread: http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-June/053825.html
20-06-2018

Review thread from December 2017: http://mail.openjdk.java.net/pipermail/core-libs-dev/2017-December/050325.html
08-06-2018

I think Paul volunteered you to take this one, Chris. :-)
13-02-2015

The obvious default implementation would be something like return toArray(generator.apply(this.size())); however, this would return an array of the wrong size if the collection changes size between the calls to size() and toArray(). A safer (though perhaps less efficient) default might be return toArray(generator.apply(0));
03-11-2014