Why does the following code throw ArrayStoreException
?
double[] a = {2.0,3.4,3.6,2.7,5.6};
int[] b = {2,3,4,5};
System.arraycopy(b,0,a,1,4);
Why does the following code throw ArrayStoreException
?
double[] a = {2.0,3.4,3.6,2.7,5.6};
int[] b = {2,3,4,5};
System.arraycopy(b,0,a,1,4);
Yeah, that's the documented behavior for an arraycopy
between arrays with different primitive types as components. Whether the type could normally be promoted isn't relevant; this is what arraycopy
is designed to do.
There is no automatic conversion between int and double elements in the array with arraycopy(). The native method checks for array type equivalence and throws the ArrayStoreException on mismatch. You'll have to revert to the plain or method of looping:
for (int i = 0; i < a.length(); i++)
a[i] = b[i];
From the docs for System.arraycopy
:
Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:
[...]
The src argument and dest argument refer to arrays whose component types are different primitive types.
That's exactly the case here - int
and double
are different primitive types, so the exception is thrown as documented.
The point of arraycopy
is that it can work blindingly fast by copying the raw data blindly, without having to apply any conversions. In your case it would have to apply conversions, so it fails.