📜  Java中的数组 copyOf() 和示例

📅  最后修改于: 2022-05-13 01:54:25.120000             🧑  作者: Mango

Java中的数组 copyOf() 和示例

Java.util.Arrays.copyOf() 方法在Java.util.Arrays 类中。它复制指定的数组,用 false 截断或填充(如有必要),因此副本具有指定的长度。

句法:

copyOf(int[] original, int newLength) 
  • original – 原始数组
  • newLength - 原始数组的副本
// Java program to illustrate copyof method
import java.util.Arrays;
  
public class Main
{
    public static void main(String args[])
    {
        // initializing an array original
        int[] org = new int[] {1, 2 ,3};
  
        System.out.println("Original Array");
        for (int i = 0; i < org.length; i++)
            System.out.print(org[i] + " ");
  
        // copying array org to copy
        int[] copy = Arrays.copyOf(org, 5);
  
        // Changing some elements of copy
        copy[3] = 11;
        copy[4] = 55;
  
        System.out.println("\nNew array copy after modifications:");
        for (int i = 0; i < copy.length; i++)
            System.out.print(copy[i] + " ");
    }
}

输出:

Original Array
1 2 3 
New array copy after modifications:
1 2 3 11 55 

如果复制数组的长度大于原始数组会怎样?
对于在原始数组和新数组中有效的所有索引,这两个数组将具有相同的值。
但是,如果复制的数组长度大于原始数组,则原始中缺少的索引将为零

// Java program to illustrate copyOf when new array
// is of higher length.
import java.util.Arrays;
  
public class Main 
{
  public static void main(String args[]) 
  {
      // initializing an array original
      int[] org = new int[] {1, 2 ,3};
     
      System.out.println("Original Array : \n");
      for (int i = 0; i < org.length; i++)
           System.out.print(org[i] + " ");  
        
       // copying array org to copy 
       // Here, new array has 5 elements - two
       // elements more than the original array
       int[] copy = Arrays.copyOf(org, 5);
    
       System.out.print("\nNew array copy (of higher length):\n");
       for (int i = 0; i < copy.length; i++) 
           System.out.print(copy[i] + " ");
    }
}

输出:

Original Array : 
1 2 3 
New array copy (of higher length):
1 2 3 0 0