import java.lang.reflect.Array; public class ArraysUtils { /** *@來源 org.apache.commons.lang *@apiNote把數組A和數組B合併到一個數組 * */ public static Object[] addArrays(Object[] A, Object[] B) { if (A == null) { return clone(B); } else if (B == null) { return clone(A); } Object[] joinedArray = (Object[]) Array.newInstance(A.getClass().getComponentType(), A.length + B.length); System.arraycopy(A, 0, joinedArray, 0, A.length); try { System.arraycopy(B, 0, joinedArray, A.length, B.length); } catch (ArrayStoreException ase) { //須要保證合併的對象類型相同 final Class<?> type1 = A.getClass().getComponentType(); final Class<?> type2 = B.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)) { throw new IllegalArgumentException("Cannot store " + type2.getName() + " in an array of " + type1.getName()); } throw ase; } return joinedArray; } private static Object[] clone(Object[] array) { if (array == null) { return null; } return (Object[]) array.clone(); } public static void main(String[] args) { Integer[] a = { 1, 2, 3, 4, 5 }; Short[] b = { 9, 7, 8, 9 }; Object[] addAll = addArrays(a, b); for (int i = 0; i < addAll.length; i++) { System.out.println(addAll[i]); } } }