Reputation: 45
I wanted to copy array from one Integer array into another array many times.
int a[6]={1,2,3};
int b[]=new int[12];
for(int i=0;i<12;i++)
{
b[i]=a[i];
System.out.println(b[i]);
}
I wanted output like this:
1,2,3,1,2,3,1,2,3,1,2,3
How should i copy all element from a[] to b[] for as many times i want.
Upvotes: 2
Views: 2276
Reputation: 6716
The most efficient way to do what you want (that I can think of) is to copy batches.
So we got our two input arrays:
int a[] = {1, 2, 3};
int b[] = new int[12];
What we want to do is to copy the first array into the second until again and again in sequence until the second array is filled.
The first batch is simple. Just copy the first array once into the second.
System.arraycopy(a, 0, b, 0, a.length);
And now we copy what we append the data in the second array to the free fields of the second array.
int usedSize = a.length;
while (usedSize < b.length) {
System.arraycopy(b, 0, b, usedSize, Math.min(b.length - usedSize, usedSize);
usedSize *= 2;
}
Your array b
will change in the following way:
{1,2,3,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x}
{1,2,3,1,2,3,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x}
{1,2,3,1,2,3,1,2,3,1,2,3,x,x,x,x,x,x,x,x,x,x,x,x}
{1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}
So it reduced the copy step required and will work very fast even for big arrays. System.arraycopy
is in the end the fastest way to copy array contents around.
Upvotes: 1
Reputation: 393831
You can use modulus operator :
for(int i=0;i<12;i++)
{
b[i]=a[i%a.length];
System.out.println(b[i]);
}
i%a.length
will iterate repeatedly from 0 to a.length-1.
Upvotes: 6