Monday 23 October 2017

Merge generic arrays

In this post, I am going to show you how to merge generic arrays.

First, we need to define a generic array, that takes variable number of generic arrays as arguments and return a generic array. Method signature looks like below.
public static <T> T[] mergeArrays(T[]... arr)


Next, we need to identify the size of the resulting (after merging all the elements of input arrays) array.


Below snippet is used to calculate the length of output array.
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

Define generic array with length ‘finalArraySize’. By using reflection, we can define gneric array.
T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);

Now, you can copy all the input array elements to result array. I am using System.arraycopy method to copy elements of array.
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }


Find the below working application.


Test.java
import java.lang.reflect.Array;

public class Test {
 @SuppressWarnings("unchecked")
 public static <T> T[] mergeArrays(T[]... arr) {
  if (arr == null) {
   return null;
  }
  int finalArraySize = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;
   finalArraySize += array.length;
  }

  /* Define array with given size */
  T[] result = (T[]) Array.newInstance(arr[0].getClass().getComponentType(), finalArraySize);
  int offset = 0;

  for (T[] array : arr) {
   if (array == null)
    continue;

   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }

  return result;
 }

 private static void printArray(Object[] arr) {
  for (Object data : arr) {
   System.out.print(data + " ");
  }
 }

 public static void main(String args[]) {
  Integer[] arr1 = { 2, 3, 5, 7 };
  Integer[] arr2 = { 1, 3, 5, 7, 11 };
  Integer[] arr3 = null;
  Integer[] arr4 = { 2, 4, 6, 8, 10 };

  Integer[] result = mergeArrays(arr1, arr2, arr3, arr4);
  printArray(result);

 }
}




No comments:

Post a Comment