什么是 Java System.arraycopy() 方法?
Java System.arraycopy()方法声明
java.lang类中java.lang.System.arraycopy()方法的方法声明如下:
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) 个元素的dest 数组。返回值
arraycopy方法有一个void返回类型,这意味着它不返回任何东西 。例子
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
改变参数的例子
// Example of changing parameters
srcIndex = 4;
destIndex = 5;
len = 1;
输出
len : 1 srcIndex : 4 src : Monday Tuesday Wednesday Thursday Friday Saturday Sunday destIndex : 5 dest : January February March April May June July July August 最终目的地数组:January February March April May Friday July August
GO TO FULL VERSION