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.
a[6]for example and that exceeds the size of the array. Also your array initialization is not correct. Now to prepare a good answer: Do you really need theprintlnoutput? This will prevent batch copies.printlnoutput Erans answer is the way to go. That doesn't work with my proposal. If you want to transfer the data from arrayatobboth answer work.