kailash gaur
kailash gaur

Reputation: 1447

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

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?

Upvotes: 16

Views: 38506

Answers (5)

Colin D
Colin D

Reputation: 5661

To solve this, simply iterate over the small array and add them to the larger array.

   for(int i = 0; i < arr1.length(); ++i) {
      arr[i] = arr1[i];
    }

Upvotes: 6

kakarott
kakarott

Reputation: 211

for (int i = 0; i < 4; i++) 
{
arr[i] = arr1[i];
}

will do the job.

Upvotes: 0

NominSim
NominSim

Reputation: 8511

If you want to keep the values in arr that are beyond the length of arr1 do:

for(int i = 0; i < arr1.length(); i++){
    if(i < arr.length()){ // Just in case arr isn't larger
        arr[i] = arr1[i];
    }
}

If you want to reset the values in arr that are beyond the length of arr1 do:

for(int i = 0; i < arr.length(); i++){
    if(i < arr1.length()){ // Just in case arr isn't larger
        arr[i] = arr1[i];
    } else {
        arr[i] = 0; // Or whatever default value you want here
    }
}

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234847

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

Upvotes: 43

Matzi
Matzi

Reputation: 13925

This seems to be a very easy question:

for (int i = 0; i < 4; i++) arr[i] = arr1[i];

Upvotes: 4

Related Questions