Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a small array into a larger one without changing the target array's size

Tags:

java

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?

like image 973
kailash gaur Avatar asked Jun 22 '12 15:06

kailash gaur


2 Answers

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)));
like image 86
Ted Hopp Avatar answered Sep 29 '22 15:09

Ted Hopp


This seems to be a very easy question:

for (int i = 0; i < 4; i++) arr[i] = arr1[i];
like image 34
Matzi Avatar answered Sep 29 '22 15:09

Matzi