JDK-8176893 : Release Note: Arrays.asList().toArray() returns Object[]
  • Type: Sub-task
  • Component: core-libs
  • Sub-Component: java.util:collections
  • Affected Version: 9
  • Priority: P3
  • Status: Closed
  • Resolution: Delivered
  • Submitted: 2017-03-16
  • Updated: 2017-09-22
  • Resolved: 2017-03-16
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.
The `Arrays.asList()` API returns an instance of `List`. Calling the `toArray()` method on that `List` instance is specified always to return `Object[]`, that is, an array of `Object`. In previous releases, it would sometimes return an array of some subtype. Note that the declared return type of `Collection.toArray()` is `Object[]`, which permits an instance of an array of a subtype to be returned. The specification wording, however, clearly requires an array of `Object` to be returned.

The `toArray()` method has been changed to conform to the specification, and it now always returns `Object[]`. This may cause code that was expecting the old behavior to fail with a `ClassCastException`. An example of code that worked in previous releases but that now fails is the following:
    List<String> list = Arrays.asList("a", "b", "c");
    String[] array = (String[]) list.toArray();
If this problem occurs, rewrite the code to use the one-arg form `toArray(T[])`, and provide an instance of the desired array type. This will also eliminate the need for a cast.
    String[] array = list.toArray(new String[0]);