In some cases, we would like to merge a few byte arrays into one. This is also known as concatenating the arrays. We can use the following Java utility/static function to do so:
public class ArrayUtils {
/**
* merge arrays.
*
* @param arrays - arrays to merge
* @return - merged array
*/
public static byte[] merge(byte[]... arrays) {
var count = 0;
// obtain the total length of the merged array
for (var array : arrays) {
count += array.length;
}
// copy all the arrays into the new array
var result = new byte[count];
int start = 0;
for (var array : arrays) {
System.arraycopy(array, 0, result, start, array.length);
start += array.length;
}
return result;
}
}
The idea is to first compute the result’s array’s length, and then copy over each array one by one. Example usage:
var arr1 = new byte[3] {1, 2, 3};
var arr2 = new byte[3] {4, 5, 6};
var result = Arrays.merge(arr1, arr2); // contains {1, 2, 3, 4, 5, 6}
We can pass as many arrays as we want as we are using the triple dots syntax to allow variant length of parameters in Java.
–EOF (The Ultimate Computing & Technology Blog) —
213 wordsLast Post: Teaching Kids Programming - Remove One Number to Make Average
Next Post: Teaching Kids Programming - Implementation of Cartesian Product in Python via Depth First Search Algorithm