Make copy of an array

前端 未结 11 2392
庸人自扰
庸人自扰 2020-11-21 23:05

I have an array a which is constantly being updated. Let\'s say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call

11条回答
  •  無奈伤痛
    2020-11-21 23:45

    You can also use Arrays.copyOfRange.

    Example:

    public static void main(String[] args) {
        int[] a = {1,2,3};
        int[] b = Arrays.copyOfRange(a, 0, a.length);
        a[0] = 5;
        System.out.println(Arrays.toString(a)); // [5,2,3]
        System.out.println(Arrays.toString(b)); // [1,2,3]
    }
    

    This method is similar to Arrays.copyOf, but it's more flexible. Both of them use System.arraycopy under the hood.

    See:

    • https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
    • https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
    • http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/Arrays.java?av=f

提交回复
热议问题