Java, merging two arrays evenly

Posted by user2435044 on Stack Overflow See other posts from Stack Overflow or by user2435044
Published on 2013-06-27T21:42:53Z Indexed on 2013/06/27 22:21 UTC
Read the original article Hit count: 181

Filed under:
|
|

What would be the best way to merge two arrays of different lengths together so they are evenly distributed in the new array?

Say I have the following arrays

 String[] array1 = new String[7];
 String[] array2 = new String[2];
 String[] mergedArray = new String[array1.length + array2.length];

I would want mergedArray to have the following elements

array1 array1 array1 array2 array1 array1 array1 array2 array1

but if I were to change the size of the arrays to

 String[] array1 = new String[5];
 String[] array2 = new String[3];
 String[] mergedArray = new String[array1.length + array2.length];

then I would want it to be

array1 array2 array1 array2 array1 array2 array1 array1

basically if it can be helped each array2 element shouldn't be touching each other; exception if array2 has a size larger than array1.

© Stack Overflow or respective owner

Related posts about java

Related posts about arrays