Java 复制数组

在 Java 中,我们可以将一个 数组 复制到另一个数组。您可以使用多种技术来复制 Java 数组。


1. 使用赋值运算符复制数组

我们来看一个例子,

class Main {
    public static void main(String[] args) {
       
        int [] numbers = {1, 2, 3, 4, 5, 6};
        int [] positiveNumbers = numbers;    // copying arrays

        for (int number: positiveNumbers) {
            System.out.print(number + ", ");
        }
    }
}

输出:

1, 2, 3, 4, 5, 6

在上面的示例中,我们使用赋值运算符 (=) 将一个名为 numbers 的数组复制到另一个名为 positiveNumbers 的数组。

这种技术是最简单的,并且有效。但是,这种技术存在一个问题。如果我们更改一个数组的元素,另一个数组的相应元素也会更改。例如,

class Main {
    public static void main(String[] args) {
      
        int [] numbers = {1, 2, 3, 4, 5, 6};
        int [] positiveNumbers = numbers;    // copying arrays
      
        // change value of first array
        numbers[0] = -1;

        // printing the second array
        for (int number: positiveNumbers) {
            System.out.print(number + ", ");
        }
    }
}

输出:

-1, 2, 3, 4, 5, 6

在这里,我们可以看到我们更改了 numbers 数组的一个值。当我们打印 positiveNumbers 数组时,我们可以看到相同的值也发生了更改。

这是因为两个数组都引用同一个数组对象。这是由于浅拷贝。要了解有关浅拷贝的更多信息,请访问 浅拷贝

现在,为了在复制数组时创建新的数组对象,我们需要深拷贝而不是浅拷贝。


2. 使用循环结构复制数组

我们来看一个例子

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int [] source = {1, 2, 3, 4, 5, 6};
        int [] destination = new int[6];

        // iterate and copy elements from source to destination
        for (int i = 0; i < source.length; ++i) {
            destination[i] = source[i];
        }
      
         // converting array to string
        System.out.println(Arrays.toString(destination));
    }
}

输出:

[1, 2, 3, 4, 5, 6]

在上面的示例中,我们使用 for 循环 来迭代源数组的每个元素。在每次迭代中,我们都将元素从 source 数组复制到 destination 数组。

在这里,源数组和目标数组引用不同的对象(深拷贝)。因此,如果更改一个数组的元素,另一个数组的相应元素将不会更改。

请注意以下语句:

System.out.println(Arrays.toString(destination));

在这里,toString() 方法用于将数组转换为字符串。要了解更多信息,请访问 toString() 方法(官方 Java 文档)


3. 使用 arraycopy() 方法复制数组

在 Java 中,System 类包含一个名为 arraycopy() 的方法来复制数组。此方法比前两种方法是复制数组的更好方法。

arraycopy() 方法允许您将源数组的指定部分复制到目标数组。例如,

arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

这里,

  • src - 您要复制的源数组
  • srcPos - 源数组中的起始位置(索引)
  • dest - 要从源复制元素的目录数组
  • destPos - 目录数组中的起始位置(索引)
  • length - 要复制的元素数量

我们来看一个例子

// To use Arrays.toString() method
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] n1 = {2, 3, 12, 4, 12, -2};
      
        int[] n3 = new int[5];

        // Creating n2 array of having length of n1 array
        int[] n2 = new int[n1.length];
      
        // copying entire n1 array to n2
        System.arraycopy(n1, 0, n2, 0, n1.length);
        System.out.println("n2 = " + Arrays.toString(n2));  
      
        // copying elements from index 2 on n1 array
        // copying element to index 1 of n3 array
        // 2 elements will be copied
        System.arraycopy(n1, 2, n3, 1, 2);
        System.out.println("n3 = " + Arrays.toString(n3));  
    }
}

输出:

n2 = [2, 3, 12, 4, 12, -2]
n3 = [0, 12, 4, 0, 0]

在上面的示例中,我们使用了 arraycopy() 方法,

  • System.arraycopy(n1, 0, n2, 0, n1.length) - n1 数组的全部元素被复制到 n2 数组
  • System.arraycopy(n1, 2, n3, 1, 2) - n1 数组从索引 2 开始的 2 个元素被复制到 n3 数组从索引 1 开始的位置

如您所见,int 类型数组元素的默认初始值为 0。


4. 使用 copyOfRange() 方法复制数组

我们还可以使用 Java Arrays 类中定义的 copyOfRange() 方法来复制数组。例如,

// To use toString() and copyOfRange() method
import java.util.Arrays;

class ArraysCopy {
    public static void main(String[] args) {
      
        int[] source = {2, 3, 12, 4, 12, -2};
      
        // copying entire source array to destination
        int[] destination1 = Arrays.copyOfRange(source, 0, source.length);      
        System.out.println("destination1 = " + Arrays.toString(destination1)); 
      
        // copying from index 2 to 5 (5 is not included) 
        int[] destination2 = Arrays.copyOfRange(source, 2, 5); 
        System.out.println("destination2 = " + Arrays.toString(destination2));   
    }
}

输出

destination1 = [2, 3, 12, 4, 12, -2]
destination2 = [12, 4, 12]

在上面的示例中,请注意这一行:

int[] destination1 = Arrays.copyOfRange(source, 0, source.length);

在这里,我们可以看到我们正在创建 destination1 数组,并在调用 copyOfRange() 方法的同时将其复制到 source 数组。我们没有在调用 copyOfRange() 方法之前创建 destination1 数组。要了解有关该方法的更多信息,请访问 Java copyOfRange


5. 使用 Loop 复制 2d 数组

与一维数组类似,我们也可以使用 for 循环复制二维数组。例如,

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int[][] source = {
              {1, 2, 3, 4}, 
              {5, 6},
              {0, 2, 42, -4, 5}
              };

        int[][] destination = new int[source.length][];

        for (int i = 0; i < destination.length; ++i) {

            // allocating space for each row of destination array
            destination[i] = new int[source[i].length];

            for (int j = 0; j < destination[i].length; ++j) {
                destination[i][j] = source[i][j];
            }
        }
     
        // displaying destination array
        System.out.println(Arrays.deepToString(destination));  
      
    }
}

输出:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

在上面的程序中,请注意以下行:

System.out.println(Arrays.deepToString(destination);

在这里,deepToString() 方法用于提供二维数组的更好表示。要了解更多信息,请访问 Java deepToString()


使用 arraycopy() 复制 2d 数组

为了使上面的代码更简单,我们可以像一维数组一样,用 System.arraycopy() 替换内部循环。例如,

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
      
        int[][] source = {
              {1, 2, 3, 4}, 
              {5, 6},
              {0, 2, 42, -4, 5}
              };

        int[][] destination = new int[source.length][];

        for (int i = 0; i < source.length; ++i) {

             // allocating space for each row of destination array
             destination[i] = new int[source[i].length];
             System.arraycopy(source[i], 0, destination[i], 0, destination[i].length);
        }
     
        // displaying destination array
        System.out.println(Arrays.deepToString(destination));      
    }
}

输出:

[[1, 2, 3, 4], [5, 6], [0, 2, 42, -4, 5]]

在这里,我们可以看到,通过用 arraycopy() 方法替换内部 for 循环,我们得到了相同的输出。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战