Make copy of an array

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

    Nice explanation from http://www.journaldev.com/753/how-to-copy-arrays-in-java

    Java Array Copy Methods

    Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.

    System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.

    Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use.

    Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.

提交回复
热议问题