< prev index next >
src/java.base/share/classes/java/util/Collection.java
Print this page
rev 48060 : 8060192: Add default method <A> A[] Collection.toArray(IntFunction<A[]> generator)
Reviewed-by: XXX
*** 23,32 ****
--- 23,33 ----
* questions.
*/
package java.util;
+ import java.util.function.IntFunction;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
*** 327,336 ****
--- 328,374 ----
* runtime component type} of the specified array
* @throws NullPointerException if the specified array is null
*/
<T> T[] toArray(T[] a);
+ /**
+ * Returns an array containing all of the elements in this collection,
+ * using the provided {@code generator} function to allocate the returned array.
+ *
+ * <p>If this collection makes any guarantees as to what order its elements
+ * are returned by its iterator, this method must return the elements in
+ * the same order.
+ *
+ * <p>Like the {@link #toArray()} method, this method acts as bridge between
+ * array-based and collection-based APIs. Further, this method allows
+ * precise control over the runtime type of the output array.
+ *
+ * <p>Suppose {@code x} is a collection known to contain only strings.
+ * The following code can be used to dump the collection into a newly
+ * allocated array of {@code String}:
+ *
+ * <pre>
+ * String[] y = x.toArray(String[]::new);</pre>
+ *
+ * @implSpec
+ * The default implementation calls the generator function with zero
+ * and then passes the resulting array to {@link #toArray(T[])}.
+ *
+ * @param <T> the component type of the array to contain the collection
+ * @param generator a function which produces a new array of the desired
+ * type and the provided length
+ * @return an array containing all of the elements in this collection
+ * @throws ArrayStoreException if the runtime type of any element in this
+ * collection is not assignable to the {@linkplain Class#getComponentType
+ * runtime component type} of array returned by the generator function
+ * @throws NullPointerException if the generator function is null
+ * @since 10
+ */
+ default <T> T[] toArray(IntFunction<T[]> generator) {
+ return toArray(generator.apply(0));
+ }
+
// Modification Operations
/**
* Ensures that this collection contains the specified element (optional
* operation). Returns {@code true} if this collection changed as a
< prev index next >