如何合并两个数组

1. 遍历两个数组放入另一个

    /*
    遍历两个int[] 遍历放入一个数组
     */
    public static int[] conTwoArrays(int[] a,int[] b){
        int[] res=new int[a.length+b.length];
        for (int i = 0; i < res.length; i++) {
            if (i<a.length){
                res[i]=a[i];
            }else {
                res[i]=b[i-a.length];
            }
        }
        return res;
    }

2. System.arraycopy

System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

    /*
    System.arraycopy: 将指定源数组中的数组从指定位置复制到目标数组的指定位置。
     */
    static String[] concat1(String[] a, String[] b) {
        String[] c= new String[a.length+b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        return c;
    }

3. Arrays.copyOf

Arrays.copyOf(T[] original, int newLength)

    /*
    Arrays.copyOf(T[] original, int newLength)
     */
    public static <T> T[] concat2(T[] first, T[] second) {
        T[] result = Arrays.copyOf(first, first.length + second.length);
        System.arraycopy(second, 0, result, first.length, second.length);
        return result;
    }

注意:基本类型数组需用其包装类型

4. 多个合并

    /*
    合并多个 (2个以上)
     */
    public static <T> T[] concatAll(T[] first, T[]... rest) {
        int totalLength = first.length;
        for (T[] array : rest) {
            totalLength += array.length;
        }
        T[] res = Arrays.copyOf(first, totalLength);
        int offset = first.length;
        for (T[] array : rest) {
            System.arraycopy(array, 0, res, offset, array.length);
            offset += array.length;
        }
        return res;
    }

测试

    public static void main(String[] args) {
        int a[] ={1,3};
        int b[] ={2,4,5};
        int[] intres = conTwoArrays(a, b);
        System.out.println(Arrays.toString(intres));

        String s[]={"a","b","c"};
        String e[]={"d","e","f"};
        String f[]={"g","h","i"};
        //System.arraycopy
        String[] res = concat1(s, e);
        System.out.println(Arrays.toString(res));

        //Arrays.copyOf(T[] original, int newLength)
        String[] res2 = concat2(s, e);
        System.out.println(Arrays.toString(res2));
        //合并整数类型需用包装类型
        Integer m[]={1,2,3};
        Integer n[]={1,2,3};
        Integer[] res3 = concat2(m, n);
        System.out.println(Arrays.toString(res3));

        String[] res4 = concatAll(s, e ,f);
        System.out.println(Arrays.toString(res4));
    }

在这里插入图片描述

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值