CodeGym/Java Blog/Toto sisi/Java 中的 Arrays.copyOf() 方法
John Squirrels
等級 41
San Francisco

Java 中的 Arrays.copyOf() 方法

在 Toto sisi 群組發布
個成員

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()方法有一個邏輯上的理解。但是,請隨意嘗試不同的輸入來激發您的好奇心。
留言
  • 受歡迎
你必須登入才能留言
此頁面尚無留言