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]);
}
}
}