How to make copy of an array in Java?
Posted by Paul on April 30th 2018 14:01 PM
There are multiple ways of making a copy of array in Java : 1. System.arraycopy(): This method provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. e.g. 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. 2. Object.clone(): clone() method is provided by object and as array in java is also an Object, you can make use of this method in order to get the full array copy. 3. Arrays.copyOfRange(): This method is helpful where you need few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array. 4. Arrays.copyOf(): When you want to copy first few elements of an array or full copy of array, you can use this method. Let's implement these methods :