天天看點

合并同類型的數組

比如我有三個int類型的數組,分别是

int[] a = { 1, 2, 3 };

int[] b = { 4, 5 };

int[] c = { 6, 8 };

想合并為一個大的數組,怎麼辦呢?

合并同類型的數組

public static int[] mergearray(int[]... a) {  

        // 合并完之後數組的總長度  

        int index = 0;  

        int sum = 0;  

        for (int i = 0; i < a.length; i++) {  

            sum = sum + a[i].length;  

        }  

        int[] result = new int[sum];  

            int lengthone = a[i].length;  

            //拷貝數組  

            system.arraycopy(a[i], 0, result, index, lengthone);  

            index = index + lengthone;  

        return result;  

    }  

//測試方法,把a、b、c三個數組合并為result(同類型的數組,長度為三個數組長度總和)  

    @test  

    public void testmerge() {  

        int[] a = { 1, 2, 3 };  

        int[] b = { 4, 5 };  

        int[] c = { 6, 8 };  

        int[] result = mergearray(a, b, c);  

        for (int i = 0; i < result.length; i++) {  

            system.out.print(result[i] + "  ");  

        system.out.println();  

        system.out.println("length:"+result.length);