java数组合并

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

 

转载于:https://www.cnblogs.com/zyf-yxm/p/11431156.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值