How to copy elements of one array to another array in Java - Arrays.copyOf and Arrays.copyOfRange Example

There are multiple ways to copy elements from one array in Java e.g. you can manually copy elements by using a loop, create a clone of the array, use Arrays.copyOf() method or System.arrayCopy() to start copying elements from one array to another in Java. Even though both allow you to copy elements from source to destination array, the Arrays.copyOf() is much easier to use as it takes the just original array and the length of the new array. But, this means you cannot copy subarray using this method because you are not specifying to and from an index, but don't worry there is another method in the java.util.Arrays class to copy elements from one index to other in Java, the Arrays.copyOfRange() method. Both methods are overloaded to copy different types of array.

For example, the Arrays.copyOf() method is overloaded 9 times to allow you to copy all primitive array and reference array e.g. you can use copyOf(originalArray, newLength) to copy booleans from a boolean array, integers from int array, characters from char array, and bytes from the array and so on.

This method copies the specified array, truncating or padding the with the default values (if necessary), depending upon the type of array it's copying, so the copy has the specified length.

For example, if it is copying from boolean array then it will pad with false if the value of new length is greater than the length of the original array.

For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain the default value for the type of array e.g. false for a boolean array, zero or byte, int, char, and long array, 0.0 for float and double array, and null for reference type array.

Such indices will exist if and only if the specified length is greater than that of the original array. Btw, if you are not familiar with array data structure itself, then I suggest you take a good online course on data structure and algorithm e.g.  Data Structures and Algorithms: Deep Dive Using Java on Udemy is a good one to find out more about essential data structure in depth.



How to copy a range of elements from one array to another in Java

The  Arrays.copyOfRange() is used to copy a range of values from one array to another in Java.  The copyOfRange(T[] original, int from, int to) takes three parameters, the original array, index of the first element or start index and index of last element or end index.  It then copies the specified range of the specified array into a new array.

The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to).

Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case default values are placed in all elements of the copy whose index is greater than or equal to original.length - from e.g. false for boolean array, zero for integral array and null for object array. 

The length of the returned array will be to - form, which means if you copy elements from 2 to 5 index then you will get the element at indices 2, 3, and 4 and length of the array will be 3 (5 - 2) = 3.

Here is some sample code to copy an array in Java, both creating exact copy and a range of indices:


 How to copy elements of one array to another array in Java - Arrays.copyOf and Arrays.copyOfRange Example


How to copy elements of one array to another

You can use the Arrays.copyOf() method to copy an array in Java. This method allows you to copy all or subset of elements from the array in Java, but elements must be consecutive e.g. first 5 or first 10 elements of the array.

This is done by specifying the length argument for the new array in the Arrays.copyOf() method.

This method is also overloaded to copy 8 types of primitive array e.g. booleanintshort, char, byte, long, float, and double as well as reference type array.

String[] creditCards = {"Chase Sapphire Preferred Card ",
                                "Chase Freedom Unlimited",
                                "Amex Credit Card",
                                "Citi Simplicity Card ",
                                "Blue Cash Preferred Card from American Express ",
                                "NASCAR Credit Card from Credit One Bank"};
        
        
// let's copy this String array into another
String[] bestCreditCards = Arrays.copyOf(creditCards, creditCards.length);
        
System.out.println("original array: " + Arrays.toString(creditCards));
System.out.println("copy of array: " + Arrays.toString(bestCreditCards));

By the way, this is not the only way to make a copy of an array. You can also use the System.arrayCopy() method to copy an array in Java. I am not explaining that here because it's a little bit difficult to use and you should not be using unless you know what you are doing. Btw, these methods internally use the System.arrayCopy() itself.

The only place you need the System.arrayCopy() is if you are working on older Java version where Arrays.copyOf() and Arrays.CopyOfRange() method is not available e.g. Java 1.5. These methods are only added in Java SE 6 but System.arrayCopy() is there from JDK 1 itself. See The Complete Java Master Class for Beginners to learn more about essential methods of JDK.




Java Program to Copy Values from One Array to Other in Java

Here is my complete Java program to show you how you can make copies of an array in Java, both primitive and reference type array, as well how you can copy as many elements you want or how to copy a range of values or a sub-array in Java.

import java.util.Arrays;

/*
 * Java Program to copy elements from one array
 * to other in Java using Arrays.copyOf and
 * Arrays.copyOfRange methods
 */
public class Hello {

  public static void main(String args[]){
    
    // original array has 10 elements
    int[] original = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
    System.out.println("original array: " + Arrays.toString(original));
    
    // let's create an exact copy of the array
    int[] copy = Arrays.copyOf(original, 10);
    System.out.println("exact copy: " + Arrays.toString(copy));
    
    // let's copy only first 5 elements
    int[] firstFive = Arrays.copyOf(original, 5);
    System.out.println("exact copy: " + Arrays.toString(firstFive));
    
    // let's create a larger array by copying
    int[] bigger = Arrays.copyOf(original, 15);
    System.out.println("bigger copy: " + Arrays.toString(bigger));
    
    // Now, let's copy a range of values from one array to another
    // copying subarray from 2nd element to 5th element
    int[] range = Arrays.copyOfRange(original, 2, 5);
    System.out.println("copying range of values 2 to 5: " 
                          + Arrays.toString(range));
  }

}

Output:
original array: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
exact copy: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
exact copy: [10, 20, 30, 40, 50]
bigger copy: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 0, 0, 0, 0, 0]
copying range of values 2 to 5: [30, 40, 50]

If you look at the original array, we have 10 elements starting from 10 to 100, the first element, which is at index zero is 10. In the first example, we have created an exact copy of the array by passing the new length same as the length of the old array and that's why Arrays.copyOf() method returned an array which was exact copy i.e. contains same elements at same indices.

In the next example, we have only copied the first five elements because the length of the new array was 5, half the length of the original array. Later we created a bigger array by supplying new length as 15, which means first 10 elements are copied from original array and rest of the indices are padded with the default values for integer (because it was an integer array), which was zero.

In the last example, I have shown you how you can copy a range or indices or a sub-array by using the Arrays.copyOfRange() method. In order to copy values from 3rd index to 5th index, we passed 2 and 5, because 3rd element resides at index 2. The start index is inclusive but end index is not, hence the new array has 3 elements, from 3rd, 4th and 5th index.


That's all about how to copy elements from one array to other in Java. You can use this trick to copy a string from one String array to another or integer from one string to other, but you cannot copy a string from a String array to an integer array because you cannot store different types of elements in an array. All elements must be of the same type. Btw, this is not the only way to copy elements from one array to other, you can also use the Arrays.copyOfRange() method to copy a subarray in Java.

Other Java array tutorials you may like:

Thanks for reading this article so far, if you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a comment. 

No comments:

Post a Comment