Make copy of an array

前端 未结 11 2378
庸人自扰
庸人自扰 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:36

    If you want to make a copy of:

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

    This is the way to go:

    int[] b = Arrays.copyOf(a, a.length);
    

    Arrays.copyOf may be faster than a.clone() on small arrays. Both copy elements equally fast but clone() returns Object so the compiler has to insert an implicit cast to int[]. You can see it in the bytecode, something like this:

    ALOAD 1
    INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
    CHECKCAST [I
    ASTORE 2
    

提交回复
热议问题