I want to copy a small array into a larger one. For example:
String arr[] = new String[10];
Now I have another small array
String arr1[] = new String[4];
I want to copy arr1 into arr without changing the larger array's length. ie arr should maintain a length of 10 and copying of all elements should be successfully.
Can anyone please tell me how can I do this?
Try this:
System.arraycopy(arr1, 0, arr, 0, arr1.length);
The size of arr will not change (that is, arr.length == 10 will still be true), but only the first arr1.length elements will be changed. If you want the elements of arr1 to be copied into arr starting somewhere other than the first element, just specify where:
System.arraycopy(arr1, 0, arr, offset, arr1.length);
If there's a possibility that the offset is so large that the result would run off the end of the destination array, you need to check for that to avoid an exception:
System.arraycopy(arr1, 0, arr, offset,
Math.max(0, Math.min(arr1.length, arr.length - offset - arr1.length)));
This seems to be a very easy question:
for (int i = 0; i < 4; i++) arr[i] = arr1[i];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With