วิธีการ Arrays.copyOf() ใน Java คืออะไร?
คลาส Java java.util.Arraysมีเมธอดชื่อArrays.copyOf()ที่ส่งคืนสำเนาของอาร์เรย์ที่ส่งผ่านเป็นพารามิเตอร์ไปยังฟังก์ชันนี้ ตามด้วยการระบุขนาด นี่คือส่วนหัวของวิธีการเพื่อความเข้าใจอย่างรวดเร็ว
Arrays.copyOf(int[] templateArray, int length);
โปรดทราบว่าพารามิเตอร์ที่สอง "ความยาว" คือขนาดของอาร์เรย์การคัดลอกที่คุณต้องการสร้าง ตรงนี้เรามีได้ 3 กรณี
- ความยาวของเทมเพลตและอาร์เรย์การคัดลอกจะเท่ากัน
- ความยาวของอาร์เรย์การคัดลอกจะมากกว่าความยาวของอาร์เรย์เทมเพลต
- ความยาวของอาร์เรย์การคัดลอกน้อยกว่าความยาวของอาร์เรย์เทมเพลต
ตัวอย่างการเข้ารหัส
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]
GO TO FULL VERSION