JDK-8160406 : Collection.toArray() spec should be explicit about returning precisely an Object[]
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Priority: P4
  • Status: Closed
  • Resolution: Fixed
  • Submitted: 2016-06-27
  • Updated: 2017-12-18
  • Resolved: 2017-11-30
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
CSR :  
Relates :  
Relates :  
Description
Collection.toArray() is specified to return an object of type Object[], but since arrays are covariant, that requirement is met by any array of a subtype of Object, for example, String[].

It's subtle, but it's clearly, if not explicitly, a bug to return an array of a subtype. See JDK-6260652.

Interestingly, the specification for toArray(T[]) says

    Note that toArray(new Object[0]) is identical in function to toArray().

which is a fine statement, but it's in the wrong place. There should be a requirement in the toArray() spec that it returns an instance whose runtime type is precisely Object[].
Comments
Review thread: http://mail.openjdk.java.net/pipermail/core-libs-dev/2017-November/050234.html There is also some imprecision in the toArray() and toArray(T[]) methods about how it describes array types, array component types, and runtime types, that I'll also fix as part of this changeset.
30-11-2017

This has resulted in some confusion on Stack Overflow. See http://stackoverflow.com/questions/38020766/different-behaviour-during-converting-a-list-of-strings-to-string-array
27-06-2016