1

I have an array called "first" and another array called "second", both arrays are of type byte and size of 10 indexes.

I am copying the two arrays into one array called "third" of type byte too and of length 2*first.length as follow:

byte[] third= new byte[2*first.length];
for(int i = 0; i<first.length;i++){
    System.arraycopy(first[i], 0, third[i], 0, first.length);
    }   
for(int i = 0; i<second.length;i++){
    System.arraycopy(second[i], 0, third[i], first.length, first.length);
    }

but it is not copying and it throws an exception: ArrayStoreException

I read on the here that this exception is thrown when an element in the src array could not be stored into the dest array because of a type mismatch. but all my arrays are in bytes so there is no mismatch

what exactly is the problem ?

1
  • 1
    That loop is unnecessary if you use arraycopy. The other way around, arraycopy is not required if you use a loop because you're assigning the values yourself. Commented May 8, 2013 at 15:40

2 Answers 2

10

You pass System.arraycopy the array, not the array element. By passing first[i] into arraycopy as the first argument, you're passing in a byte, which (because arraycopy is declared as accepting Object for the src argument) gets promoted to Byte. So you're getting ArrayStoreException for the first reason in the list in the documentation:

...if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

The src argument refers to an object that is not an array.

Here's how you use arraycopy to copy two byte[] arrays into a third:

// Declarations for `first` and `second` for clarity
byte[] first = new byte[10];
byte[] second = new byte[10];
// ...presumably fill in `first` and `second` here...

// Copy to `third`
byte[] third = new byte[first.length + second.length];
System.arraycopy(first,  0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks to you all .. but I decided to accept this answer as for the explanation of my mistake ..
2
System.arraycopy(first, 0, third, 0, first.length);
System.arraycopy(second, 0, third, first.length, second.length);

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.