方法一:
package org.ken.array; import java.lang.reflect.Array; import java.util.Arrays; public class JoinArray { /** * @param args */ public static void main(String[] args) { Integer[] arr1 = new Integer[]{1,2,3}; Integer[] arr2 = new Integer[]{4,5,6}; Integer[] result1 = (new JoinArray()).joinArrayGeneric(arr1,arr2); System.out.println(Arrays.toString(result1)); int[] arr2_1 = new int[]{1,2,3}; int[] arr2_2 = new int[]{4,5,6}; int[] result2 = (new JoinArray()).joinArray(arr2_1,arr2_2); System.out.println(Arrays.toString(result2)); } <T> T[] joinArrayGeneric(T[]... arrays) { int length = 0; for (T[] array : arrays) { length += array.length; } final T[] result = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length); int offset = 0; for (T[] array : arrays) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } return result; } /** * 合适于int * @param arrays * @return */ int[] joinArray(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } final int[] result = new int[length]; int offset = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, offset, array.length); offset += array.length; } return result; } }
第二种,用apache commons-lang包
int [] int1 = new int[]{1,2,3}; int[] int2 = new int[]{4,5,6}; int[] result = ArrayUtils.addAll(int1, int2); System.out.println(Arrays.toString(result));