concatenate arrays of any type - java

Combining two arrays of any type

 public static  T[] concat(T[] first, T[] second) {
  T[] result = Arrays.copyOf(first, first.length + second.length);
  System.arraycopy(second, 0, result, first.length, second.length);
  return result;
 }

For combining arbitrary number of arrays

 public static  T[] concatAll(T[] first, T[]... rest) {
  int totalLength = first.length;
  for (T[] array : rest) {
   totalLength += array.length;
  }
  T[] result = Arrays.copyOf(first, totalLength);
  int offset = first.length;
  for (T[] array : rest) {
   System.arraycopy(array, 0, result, offset, array.length);
   offset += array.length;
  }
  return result;
 }

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...