RFR: 8296935: Arrays.asList().set() with wrong types throws undocumented ArrayStoreException [v8]

Tingjun Yuan duke at openjdk.org
Wed Feb 8 23:36:48 UTC 2023


On Wed, 8 Feb 2023 23:33:20 GMT, Tingjun Yuan <duke at openjdk.org> wrote:

>> Document `java.util.Arrays.asList` that the list will throw an `ArrayStoreException` when attempting to set an element with a wrong type.
>
> Tingjun Yuan has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Update Arrays.java

I've written a CSR report for this PR as below.  Could someone please help me to submit it to the JBS if it looks okay? Thank you!

---

**Compatibility Risk:** minimum

**Compatibility Risk Description:** No implementation is modified

## Summary

Document the current behavior of `java.util.Arrays.asList(Object...)` that it will throw an `ArrayStoreException` when an element of wrong type is trying to be set into the list.

## Problem

`java.util.Arrays.asList(Object...)` is a widely used method that wraps an object array into a `List`.  The specification of  methods `List.set` and `ListIterator.set` indicates that implementations should throw a `ClassCastException` when the class of the specified element prevents it from being added to this list. However when an application tries to store an element that is not compatible with the backing array component type via the returned list, an `ArrayStoreException` will be thrown instead of `ClassCastException`, which violates the `List` specification.

## Solution

Since this method is widely used, we do not change the current behavior. Instead, we document the current behavior of `java.util.Arrays.asList(Object...)` that it will throw an `ArrayStoreException` when an element of wrong type is trying to be set into the list.

## Specification

Add the following `@apiNote` section into the `java.util.Arrays.asList` specification:


     * @apiNote
     * The {@link List} returned by this method does not conform to the
     * specification for {@link List#set} and {@link ListIterator#set}.
     * It is possible for the type parameter {@code T} of the returned list
     * to differ from the array's component type. This can occur, for example,
     * if the array argument type has been upcast from its component type:
     *
     * {@snippet :
     *    String[] strings = new String[1];
     *    List<Object> objects = Arrays.asList((Object[])strings);
     * }
     *
     * Writing an element into the returned list may result in an
     * {@link ArrayStoreException} instead of {@link ClassCastException} being
     * thrown if the element is incompatible with the underlying array's
     * component type:
     *
     * {@snippet :
     *    objects.set(0, Integer.valueOf(0)); // throws ArrayStoreException
     * }

-------------

PR: https://git.openjdk.org/jdk/pull/12135


More information about the core-libs-dev mailing list