Close

Java - How to merge, append and prepend arrays?

[Updated: May 21, 2018, Created: May 18, 2018]

Java Arrays Java 

This example shows how to merge two arrays into a new array. We can also append or prepend new elements using our merge method.

package com.logicbig.example;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ArrayMerge {

  public static <T> T[] merge(T[] a, T[] b) {
      int aLen = a.length;
      int bLen = b.length;

      @SuppressWarnings("unchecked")
      T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
      System.arraycopy(a, 0, c, 0, aLen);
      System.arraycopy(b, 0, c, aLen, bLen);
      return c;
  }

  public static <T> T[] append(T[] a, T... b) {
      return merge(a, b);
  }

  public static <T> T[] prepend(T[] a, T... b) {
      return merge(b, a);
  }

  public static void main(String[] args) {
      Integer[] ints1 = {1, 2, 3};
      Integer[] ints2 = {5, 6, 7};

      //merging
      Integer[] merged = merge(ints1, ints2);
      System.out.println(Arrays.toString(merged));

      //appending
      Integer[] append = append(ints1, 10, 11, 12);
      System.out.println(Arrays.toString(append));

      //prepending
      Integer[] prepend = prepend(ints1, -3, -2, -1);
      System.out.println(Arrays.toString(prepend));
  }
}
[1, 2, 3, 5, 6, 7]
[1, 2, 3, 10, 11, 12]
[-3, -2, -1, 1, 2, 3]

See Also