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
相關用法
- Java EnumSet copyOf()用法及代碼示例
- Java Java.util.Arrays.equals()用法及代碼示例
- Java Arrays.toString()用法及代碼示例
- Java Arrays.binarySearch()方法用法及代碼示例
- Java Arrays.sort()用法及代碼示例
- Java Arrays.fill()用法及代碼示例
- Java Arrays asList()用法及代碼示例
- Java 8 Arrays parallelSort()用法及代碼示例
- Java Java.util.Arrays.deepEquals()用法及代碼示例
- Java Java.util.Arrays.copyOfRange()用法及代碼示例
注:本文由純淨天空篩選整理自 Arrays copyOf() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。