JDK-8177290 : add copy factory methods for unmodifiable List, Set, Map
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 10
  • Priority: P3
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2017-03-21
  • Updated: 2018-02-15
  • Resolved: 2017-12-04
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 10
10 b35Fixed
Related Reports
Blocks :  
CSR :  
Relates :  
Sub Tasks
JDK-8197976 :  
Description
Probably something like this on List:

    static <T> List<T> copyOf(Collection<? extends T> coll)

This would return an unmodifiable List. There would be similar factory methods for Set and Map. This would be implemented the obvious way for most cases. 

In addition, this could check the implementation of the collection being copied from, and if it's a class that's known to be immutable, it would simply return that reference.

This would be a shallow copy.

This would also allow variant aliasing of collections, which generally isn't permitted. For example,

    List<String> list = List.of(...);
    List<CharSequence> newList = List.copyOf(list);

This can't be done for mutable collections, since it can lead to heap pollution. Since these implementations are unmodifiable, this should be safe.

Short-circuiting of copying is one of the oft-cited use cases for exposing immutable collection types. It's also one of the reasons people sometimes ask for a test method that returns whether the collection is or isn't unmodifiable. The copy factories could help mitigate some of the demand for those mechanisms.