Merging arrays in Java

I was playing around with java arrays and ran into a problem where I wanted to merge smaller arrays into a single big array. So the first thing I thought was to make a new array of size equal to the total length of all smaller arrays and then populating the values using loops. Then I went on to make a generic method to merge Generic arrays of same type but I realized that I cannot create a Generic array. So I thought of another way to merge Generic arrays using List.

public <T> T[] merge(T[]... arrays) {
List<T> list = new ArrayList<T>();

for( T[] array : arrays )
  list.addAll( Arrays.asList( array ) );

  return list.toArray( (T[]) Array.newInstance( arrays[0][0].getClass(), list.size() ) );

This code here will merge any number of generic arrays into one single array. The last line gives an unchecked cast warning, but can be ignored because we already assumed that the arrays are of same type.

Leave a Reply