On Sat, 21 Nov 2020 11:22:55 GMT, Rémi Forax <github.com+828220+fo...@openjdk.org> wrote:
>> `listFromTrustedArrayNullsAllowed` is clearly not an option, as it will >> produce shared-secret leaking (see >> [JDK-8254090](https://bugs.openjdk.java.net/browse/JDK-8254090) for a >> similar case). StreamEx solution is dirty as it relies on the implementation >> detail. I believe, OpenJDK team is not very interested in providing optimal >> implementations for third-party stream implementations, as third-party >> implementations will likely update by themselves when necessary. At least, >> my suggestion to make the default `mapMulti` implementation better was >> declined. > > This implementation duplicates the array twice, once in this.toArray() and > once in the constructor of ArrayList that calls toArray() on > Collections.ArrayList. > > I'm sure there is a better way In `ReferencePipeline` class we have: @Override public final Object[] toArray() { return toArray(Object[]::new); } @Override @SuppressWarnings("unchecked") public final <A> A[] toArray(IntFunction<A[]> generator) { ... @SuppressWarnings("rawtypes") IntFunction rawGenerator = (IntFunction) generator; return (A[]) Nodes.flatten(evaluateToArrayNode(rawGenerator), rawGenerator) .asArray(rawGenerator); } In `Nodes` class we have: public static <T> Node<T> flatten(Node<T> node, IntFunction<T[]> generator) { if (node.getChildCount() > 0) { ... T[] array = generator.apply((int) size); new ToArrayTask.OfRef<>(node, array, 0).invoke(); return node(array); } else { return node; } } It looks like it is required to implement `toList` method in a similar way in order to avoid array copy. i.e. there will be `IntFunction<List<T>> generator` which will generate 'ArrayList' with specified size and the list's `add` method will be called to add elements to the list. ------------- PR: https://git.openjdk.java.net/jdk/pull/1026