RFR(m): 8177290 add copy factory methods for unmodifiable List, Set, Map

Stuart Marks stuart.marks at oracle.com
Wed Nov 1 19:25:21 UTC 2017


On 10/31/17 5:52 PM, Bernd Eckenfels wrote:
> Having a List.of(List) copy constructor would save an additional array copy in the collector Which uses  (List<T>)List.of(list.toArray())

The quickest way to get all the elements from the source collection is to call 
toArray() on it. Some copy constructors (like ArrayList's) simply use the 
returned array for internal storage. This saves a copy, but it relies on the 
source collection's toArray() implementation to be correct. In particular, the 
returned array must be freshly created, and that array must be of type Object[]. 
If either of these is violated, it will break the ArrayList.

The "immutable" collections behind List.of/copyOf/etc. are fastidious about 
allocating their internal arrays in order to ensure that they are referenced 
only from within the newly created collection. This requires making an "extra" 
copy of the array returned by toArray().

An alternative is for the new collection to preallocate its internal array using 
the source's size(), and then to copy the elements out. But the source's size 
might change during the copy (e.g., if it's a concurrent collection) so this 
complicates things.

I think the only safe way to avoid the extra copy is to create a private 
interface that can be used by JDK implementations.

s'marks


More information about the core-libs-dev mailing list