Java self - copy the array Array

How to copy an array of Java

Length of the array is immutable, once the dispensing good space is long, it is long, it does not increase nor decrease

Step 1: Copy array

The value of an array, copying the other array,

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

src: the source array
srcPos: copying data from a start position of the source array
dest: destination array
destPos: copy start position to the destination array
length: duplicated length

public class HelloWorld {
    public static void main(String[] args) {
        int a [] = new int[]{18,62,68,82,65,9};
         
        int b[] = new int[3];//分配了长度是3的空间,但是没有赋值
         
        //通过数组赋值把,a数组的前3位赋值到b数组
         
        //方法一: for循环
         
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i];
        }
        
        //方法二: System.arraycopy(src, srcPos, dest, destPos, length)
        //src: 源数组
        //srcPos: 从源数组复制数据的启始位置
        //dest: 目标数组
        //destPos: 复制到目标数组的启始位置
        //length: 复制的长度       
        System.arraycopy(a, 0, b, 0, 3);
         
        //把内容打印出来
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i] + " ");
        }
 
    }
}

Exercise : the merge array

(Two arrays is first prepared, the length of They random number between 5-10, and uses a random number to initialize the two arrays
and then preparing a third array, the length of the third array and the first two
by System.arraycopy to the front two arrays into a third array)
Array merge

Guess you like

Origin www.cnblogs.com/jeddzd/p/11404543.html