Details
-
CSR
-
Status: Closed
-
P3
-
Resolution: Approved
-
None
-
minimal
-
-
Java API
-
SE
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.
Attachments
Issue Links
- csr of
-
JDK-8060192 Add default method <A> A[] Collection.toArray(IntFunction<A[]> generator)
-
- Resolved
-