JDK-8193155 : Add default method A[] Collection.toArray(IntFunction generator)
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P3
  • Status: Closed
  • Resolution: Approved
  • Fix Versions: 11
  • Submitted: 2017-12-06
  • Updated: 2018-06-21
  • Resolved: 2018-06-21
Related Reports
CSR :  
Description
Summary
-------

Add a method that allows the caller to specify the type of an array to receive the contents
of a collection, while letting the collection specify the size of the array to be created.

Problem
-------

A common task is to transfer the contents of a Collection to an array. The toArray() method
will create an Object array of the right size. The caller can specify the array's component
type using the toArray(T[ ]) method. However, in general, the caller doesn't know the
correct size to allocate. The semantics are that if the array is too short, the toArray(T[ ])
method will allocate an array of the correct size and with the same component type.
Thus toArray(new Foo[0]) will always create a right-sized array with component type Foo.
This works, but it is quite roundabout. It also (usually) creates a useless zero-sized array,
though that usually isn't a big deal.

Solution
--------

Add a new API toArray(IntFunction<T[ ]> generator). The caller passes in a function
that takes an int and creates an array of the desired component type with that size.
This lets the caller specify the component type and the Collection provides the right size.
Usually the caller will pass in an array constructor reference, e.g. toArray(String[ ]::new).


Specification
-------------

A new method Collection.toArray(IntFunction<T[ ]>) is added. The other toArray()
overloads' specifications have some text adjusted and migrated into API Note sections.
This has the side effect on the corresponding methods in AbstractCollection, where
the API Note text is no longer inherited. See attached specdiff for details.


Comments
Re-approving.
21-06-2018

I've posted and updated changeset for re-review: http://mail.openjdk.java.net/pipermail/core-libs-dev/2018-June/053825.html The only changes from the previous version are in the implementations. I've attached webrev.3.zip and specdiff.3.zip that contain the latest changes. Essentially the only specification differences between specdiff.0.zip and specdiff.3.zip is a change of @since from 10 to 11. There are no other material differences. Updating and marking Finalized.
20-06-2018

A pedant might note "variables have types and objects have classes," but the discussion of such distinctions is not done consistently in the API docs and the phrase "runtime type" while informal leads the reader in the right direction. Voting to approve for 11 (with the @since tags updated to 11).
13-12-2017

OK to postpone to 11.
13-12-2017

Unless there is a compelling reason to get this into 10, I'd feel more comfortable if this went in at the start of JDK 11.
08-12-2017