วิธีการ Java System.arraycopy() คืออะไร
ประกาศวิธีการ Java System.arraycopy()
การประกาศเมธอดสำหรับ เมธอด java.lang.System.arraycopy()ในคลาสjava.langเป็นดังนี้:
public static void arraycopy(Object src, int srcIndex, Object dest, int destIndex, int len)
พารามิเตอร์
ต่อไปนี้เป็นพารามิเตอร์ของ วิธี arraycopy :-
src : เป็นอาร์เรย์ต้นทาง
-
srcIndex : เป็นดัชนีเริ่มต้นของอาร์เรย์ต้นทาง
-
dest : เป็นอาร์เรย์ปลายทาง
-
destIndex : เป็นดัชนีเริ่มต้นของอาร์เรย์ปลายทาง
-
len : เป็นจำนวนองค์ประกอบที่ต้องคัดลอกจากอาร์เรย์ต้นทางไปยังอาร์เรย์ปลายทาง
ฟังก์ชั่น
วิธีarraycopyคัดลอกข้อมูลจากsrcเริ่มจาก องค์ประกอบ srcIndexจนถึงsrcIndex +( len - 1) ไปยังอาร์เรย์ปลายทางที่destIndexจนถึงdestIndex + ( len - 1)ค่าส่งคืน
วิธี การ arraycopyมี ประเภทการส่งคืน เป็นโมฆะซึ่งหมายความว่าจะไม่ส่งคืนอะไรเลยตัวอย่าง
public class Example {
public static void main(String[] args) {
String[] src = { "Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
String[] dest = { "January", "February", "March", "April", "May", "June", "July", "August"};
int srcIndex = 2;
int destIndex = 3;
int len = 2;
//print number of elements that need to be copied
//from the source to the destination array
System.out.println("len : " + len);
//print source index
System.out.println("srcIndex : " + srcIndex);
//print elements of the source array
System.out.print("src : ");
for (int i = 0; i < src.length; i++)
System.out.print(src[i] + " ");
System.out.println("");
//print destination index
System.out.println("destIndex : " + destIndex);
//print elements of the destination array
System.out.print("dest : ");
for (int i = 0; i < dest.length; i++)
System.out.print(dest[i] + " ");
System.out.println("");
// Use of arraycopy() method
System.arraycopy(src, srcIndex, dest, destIndex, len);
// this method copies the 'len' no of elements
// from the src array to the dest array using the srcIndex
// and destIndex as reference points in both the arrays
// Print elements of destination after
System.out.print("final destination array : ");
for (int i = 0; i < dest.length; i++)
System.out.print(dest[i] + " ");
}
}
เอาต์พุต
len : 2 srcIndex : 2 src : จันทร์ อังคาร พุธ พฤหัสบดี ศุกร์ เสาร์ อาทิตย์ destIndex : 3 dest : มกราคม กุมภาพันธ์ มีนาคม เมษายน พฤษภาคม มิถุนายน กรกฎาคม สิงหาคม อาร์เรย์ปลายทางสุดท้าย : มกราคม กุมภาพันธ์ มีนาคม วันพุธ พฤหัสบดี มิถุนายน กรกฎาคม สิงหาคม
ตัวอย่างการเปลี่ยนแปลงพารามิเตอร์
// Example of changing parameters
srcIndex = 4;
destIndex = 5;
len = 1;
เอาต์พุต
len : 1 srcIndex : 4 src : จันทร์ อังคาร พุธ พฤหัสบดี ศุกร์ เสาร์ อาทิตย์ destIndex : 5 dest : มกราคม กุมภาพันธ์ มีนาคม เมษายน พฤษภาคม มิถุนายน กรกฎาคม สิงหาคม อาร์เรย์ปลายทางสุดท้าย : มกราคม กุมภาพันธ์ มีนาคม เมษายน พฤษภาคม วันศุกร์ กรกฎาคม สิงหาคม
GO TO FULL VERSION