数组的拷贝方法

2022-10-26 15:09:48 浏览数 (1)

方法一:for循环手动拷贝

代码语言:javascript复制
 private static int[] copyArray(int[] array) {
       int[] temp = new int[array.length];
        for (int i = 0; i < array.length; i  ){
            temp[i] = array[i];
        }
        return temp;
    }

方法二:Arrays.copyOf

代码语言:javascript复制
 public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6};
        int[] ret =  Arrays.copyOf(array,array.length);
        System.out.println(Arrays.toString(ret));
    }

方法三:System.arraycopy()

代码语言:javascript复制
public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6};
        int[] ret = new int[array.length];
        System.arraycopy(array, 0, ret, 0,array.length);
        System.out.println(Arrays.toString(ret));
    }

方法四:数组名.clone()

代码语言:javascript复制
 public static void main(String[] args) {
        int[] array = {1,2,3,4,5,6};
        int[] ret = array.clone();
        System.out.println(Arrays.toString(ret));
    }

0 人点赞