CodeGym/Java 博客/随机的/Java 中的 Arrays.copyOf() 方法
John Squirrels
第 41 级
San Francisco

Java 中的 Arrays.copyOf() 方法

已在 随机的 群组中发布
个会员

Java 中的 Arrays.copyOf() 方法是什么?

Java 类java.util.Arrays提供了一个名为Arrays.copyOf()的方法,该方法返回作为参数传递给此函数的数组副本,然后指定其大小。这是快速理解的方法标题。
Arrays.copyOf(int[] templateArray, int length);
请注意,第二个参数“length”是您要创建的副本数组的大小。所以这里我们可以有 3 个案例。
  • 模板和副本数组的长度相同。
  • 复制数组的长度大于模板数组的长度。
  • 复制数组的长度小于模板数组的长度。
让我们看一下编码示例,看看我们如何处理上述所有三种情况。 Java 中的 Arrays.copyOf() 方法 - 1

编码示例

import java.util.Arrays;
public class ArraysCopyOfMethod {
	public static void main(String[] args) {

	  // Initialize your templateArray which you want a copy of
        int[] templateArray = new int[] {1, 2, 3, 4, 5, 6};
        System.out.println("Template Array: " + Arrays.toString(templateArray));

        // Create a "copy" of template array using
        // Arrays.copyOf(int[] array, int arrayLength) method

        // CASE 1: Sizes of both template & copy arrays are same
        int[] copyArray1 = Arrays.copyOf(templateArray, templateArray.length);
        System.out.println("Copy Array 1: " + Arrays.toString(copyArray1));

        // CASE 2: Size of copy array > Size of template array
        // extra space in copy array is filled with zeros
        int[] copyArray2 = Arrays.copyOf(templateArray, 10);
        System.out.println("Copy Array 2: " + Arrays.toString(copyArray2));

        // CASE 3: Size of copy array < Size of template array
        // copy array is only filled with only elements in overlapping size
        int[] copyArray3 = Arrays.copyOf(templateArray, 3);
        System.out.println("Copy Array 3: " + Arrays.toString(copyArray3));
	}

}

输出

模板数组:[1, 2, 3, 4, 5, 6] 复制数组 1:[1, 2, 3, 4, 5, 6] 复制数组 2:[1, 2, 3, 4, 5, 6, 0, 0, 0, 0] 复制数组 3: [1, 2, 3]

结论

到目前为止,您必须对Java 中的Arrays.copyOf()方法有一个逻辑上的理解。但是,请随意尝试不同的输入来激发您的好奇心。
评论
  • 受欢迎
你必须先登录才能发表评论
此页面还没有任何评论