3

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);
3
  • 8
    If you claim that your code throws an exception, then you should at least post code that compiles. Commented Jun 24, 2009 at 13:59
  • +1. someone edit that to at least say double[] a and int[] b Commented Jun 24, 2009 at 15:32
  • Now that the question is properly formatted and worded, please remove your downvotes. Commented Jun 24, 2009 at 15:57

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

try double**[]** a = {2.0,3.4,3.6,2.7,5.6}; and int**[]** b

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.