System类中的arraycopy方法

来源:互联网 发布:瑞士胡椒盐包带淘宝 编辑:程序博客网 时间:2024/06/05 00:52

1.定义一个数组元素的拷贝方法,能支持任意类型的数组元素拷贝操作
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
Object:java语言中的根类,Object可以表示任意数组类型,该方法没有方法体,该方法使用了native修饰符(native表示本地方法),该方法底层使用了c/c++语言实现了Java直接调用其他语言编写好的功能。
//src:源数组 srcPos:从源数组的哪一个元素开始的索引拷贝 dest:目标数组 destPos:从目标数组的哪一个元素开始的索引粘贴 length:拷贝元素的个数
2.代码:
package com.JAVABASIS5;
public class SystemArrayCopyDemo {
public static void main(String[] args){
double[] src = new double[]{1,2,3,4,5,6,7,8,9,10};
double[] dest = new double[10];
System.arraycopy(src,2,dest,4,4); //copy中的”c”是小写,否则会出错,直接使用该方法后,得出的数组dest就为{0.0,0.0,0.0,0.0,3.0,4.0,5.0,6.0,0.0,0.0}
arrPrint(dest);//使用该方法是为了能要看到dest输出的数组是多少
}
/*static void copy(int[] src,int srcPos,int[] dest,int destPos,int length){
//不将int[] src,int[] dest,换成double[] src,double[] dest,同时还是copy(src,2,dest,4,4);会出现:The method copy(int[], int, int[], int, int) in the type SystemArrayCopyDemo is not applicable for the arguments (double[], int, double[], int, int)
//说明src,dest只能使用int类型的数组;如果不想将int[] src,int[] dest,换成double[] src,double[] dest,则将copy(src,2,dest,4,4)换成System.arraycopy(src,2,dest,4,4);则不会出错
for(int index = srcPos;index < srcPos +length;index++){ //只能使用int类型的数组
dest[destPos]=src[index];
destPos ++;
}
}
*/
static void arrPrint(double[] arr){
if(arr == null){ //防止数组为空
return;
}
String ret = “[“;
for(int i=0;i