Java - Array Array Clone


You can make a quick copy of your array using array's clone() method.

For primitive types, the cloned array will have a true copy of the original array.

For reference types, the reference of the object stored in each element of the original array is copied to the corresponding element of the cloned array.

The following code illustrates the cloning of an int array and a String array.

The return type of the clone() method is Object and you need to cast the returned value to an appropriate array type.


import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    // Create an array of 3 integers 1,2,3
    int[] ids = { 1, 2, 3 };
    // Declare an array of int named clonedIds.
    int[] clonedIds;

    // The clonedIds array has the same values as the ids array.
    clonedIds = (int[]) ids.clone();
    // Create an array of 3 strings.
    String[] names = { "A", "B", "C" };
    // Declare an array of String named clonedNames.
    String[] clonedNames;//from www . j  a  va 2 s .  co  m

    // The clonedNames array has the reference of the same three strings as the
    // names array.
    clonedNames = (String[]) names.clone();