当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Arrays 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 


相关用法


注:本文由纯净天空筛选整理自 Arrays copyOf() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。