Fundamentals 9 min read

Understanding the JDK Bug in Arrays.asList().toArray() and Its Fix in JDK 9

This article explains a long‑standing JDK bug where Arrays.asList().toArray() returns an Object[] that causes ArrayStoreException when modified, analyzes the underlying implementation differences between java.util.ArrayList and Arrays$ArrayList, and describes how the issue was finally fixed in JDK 9.

IT Services Circle
IT Services Circle
IT Services Circle
Understanding the JDK Bug in Arrays.asList().toArray() and Its Fix in JDK 9

When converting a List<String> to an array using list.toArray() , the code runs fine, but replacing the list creation with Arrays.asList("1") and then calling toArray() throws an ArrayStoreException because the returned array cannot hold an Integer element.

The java.util.ArrayList implementation of toArray() copies its internal Object[] and returns it, so storing an Integer in the resulting array is legal. In contrast, Arrays$ArrayList (the list returned by Arrays.asList() ) creates a clone of its internal array, which is actually a String[] after type erasure, and the clone retains the concrete component type. Attempting to store an Integer in this String[] triggers the exception.

The analysis shows that the static inner class Arrays$ArrayList has package‑private constructors, so it can only be instantiated via Arrays.asList() . The var‑args signature of asList creates an Object[] that is then used to build a String[] (or the appropriate component type), and the subsequent clone() preserves that concrete type.

Because the Collection.toArray() contract requires returning an Object[] , the original implementation violated the semantic expectation in some cases, leading to the bug that persisted from at least 2005 until it was fixed in JDK 9.

In JDK 9 the implementation was changed to always allocate a new Object[] and copy the elements into it, matching the behavior of java.util.ArrayList and eliminating the exception.

The article also includes the original source code of ArrayList.toArray(T[] a) and Arrays.copyOf , demonstrates how different array lengths affect the copying logic, and discusses performance and concurrency considerations when using toArray() with pre‑sized arrays.

References to the OpenJDK bug list, Alibaba Java development guidelines, and various screenshots illustrate the evolution of the bug and its resolution across JDK versions.

JavaJDKbugArrays.asListArrayStoreExceptiontoArray
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.