JDK-8203184 : List.copyOf() fails to copy sublists
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 11
  • Priority: P3
  • Status: Closed
  • Resolution: Fixed
  • Submitted: 2018-05-15
  • Updated: 2018-07-07
  • Resolved: 2018-06-21
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 11 JDK 12
11 b20Fixed 12Fixed
Related Reports
Relates :  
Description
Recent changes (JDK-8193128) to the unmodifiable collections changed the sublist implementation. This has the side effect of causing List.copyOf() no longer to make copies of sublists. This might seem like an optimization, but in this case an actual copy should be made. Copying sublists is useful because it makes a copy of a portion of the backing list, which can then be garbage collected. Making a copy also allows the result to be serializable, whereas in general sublists are not serializable. This last is actually a conformance issue, since List.copyOf() requires the result to be serializable.
Comments
var list1 = List.of("a", "b", "c"); var list2 = list1.subList(1, 2); var list3 = List.copyOf(list2); list2 == list3 // is true, should be false new ObjectOutputStream(OutputStream.nullOutputStream()).writeObject(list3); // should work, instead throws java.io.NotSerializableException The obvious fix is to change the logic in List.copyOf() to something like instanceof ImmutableCollections.AbstractImmutableList && !(instanceof ImmutableCollections.SubList) in order to determine whether the arg should be returned, but this is fairly brittle. An alternative is to delegate to a method in ImmutableCollections.AbstractImmutableList, which can then deal with copying or returning 'this' as appropriate.
15-05-2018