0
点赞
收藏
分享

微信扫一扫

如何合并两个数组

b91bff6ffdb5 2022-04-08 阅读 122
java

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

在这里插入图片描述

举报

相关推荐

0 条评论