[java basics] array merge, merge two arrays into one array

 
 

 
 

The length of the array is immutable. To merge two different arrays, it cannot be achieved by appending one array to another. A new array needs to be created, and the new array length is the sum of the two array lengths. Then import the contents of both arrays into the new array.

Let's take a look at the implementation code in detail:

    public static void main(String[] args) {

        // 两个待合并数组
        int array1[] = { 20, 10, 50, 40, 30 };
        int array2[] = { 1, 2, 3 };

        // 动态初始化数组,设置数组的长度是array1和array2长度之和
        int array[] = new int[array1.length + array2.length];

        // 循环添加数组内容
        for (int i = 0; i < array.length; i++) {

            if (i < array1.length) {                     
                array[i] = array1[i];                    
            } else {
                array[i] = array2[i - array1.length];    
            }
        }

        System.out.println("合并后:");
        for (int element : array) {
            System.out.printf("%d ", element);
        }

    }
The first line of the above code is to judge whether the current loop variable i is less than array1.length, and under this condition, the contents of the array1 array are imported into the new array, see the second line of the code. After the import of array1 array content is completed, another array array2 is imported into the new array through line 3 of the code, where the subscript of array2 should be i - array1.length.


 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325789164&siteId=291194637