Why Does Java’s toArray Sometimes Return a Non‑Object[] and Cause ArrayStoreException?
The article examines a JDK bug where CopyOnWriteArrayList and ArrayList constructors contain comments about an issue (bug 6260652) that leads to unexpected array types from toArray(), causing ArrayStoreException, and shows how to avoid it with proper type checks or Arrays.copyOf.
Background
While studying JDK source code, the author noticed bug comments in the constructors of CopyOnWriteArrayList and ArrayList that reference bug IDs 6260652 and 6515694, which actually describe the same problem that remained unfixed in JDK 8.
Case 1
This example shows that assigning a Child[] to a Father[] is allowed, but storing a Father instance into the array triggers java.lang.ArrayStoreException because the runtime type of the array remains Child[].
package com.javaedge;
public class Test {
public static void main(String[] args) {
Child[] childArray = {new Child(), new Child()};
System.out.println(childArray.getClass());
Father[] fatherArray = childArray;
System.out.println(fatherArray.getClass());
// ArrayStoreException
fatherArray[0] = new Father();
}
}Case 2
This case demonstrates that Arrays.asList("JavaEdge") returns an internal class java.util.Arrays$ArrayList, and calling list.toArray() on it returns a String[], not a generic Object[]. Consequently, attempting to store an arbitrary object into that array results in an exception.
List<String> list = Arrays.asList("JavaEdge"); // returns java.util.Arrays$ArrayList
Object[] objects = list.toArray(); // returns String[] array
// cannot store an arbitrary Object into objectsCase 3
This example shows that ArrayList.toArray() returns an Object[], allowing any object type to be stored, which differs from the behavior observed in case 2.
Conclusion
The examples prove that List<String> stringList may produce an array whose actual runtime type is not Object[]. Therefore the JDK comment “c.toArray might (incorrectly) not return Object[] (see 6260652)” is accurate. To avoid ArrayStoreException, one should check the array type before storing or use Arrays.copyOf(elementData, size, Object[].class) to guarantee an Object[] result.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaEdge
First‑line development experience at multiple leading tech firms; now a software architect at a Shanghai state‑owned enterprise and founder of Programming Yanxuan. Nearly 300k followers online; expertise in distributed system design, AIGC application development, and quantitative finance investing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
