使用 arraycopy() 方法
arraycopy() 方法位于 java.lang.System 类中,其语法形式如下:
System.arraycopy(dataType[] srcArray,int srcIndex,int destArray,int destIndex,int length)
其中,srcArray 表示原数组;srcIndex 表示原数组中的起始索引;destArray 表示目标数组;destIndex 表示目标数组中的起始索引;length 表示要复制的数组长度。 使用此方法复制数组时,length+srcIndex 必须小于等于 srcArray.length,同时 length+destIndex 必须小于等于 destArray.length。 注意:目标数组必须已经存在,且不会被重构,相当于替换目标数组中的部分元素。
它可以实现将一个数组的指定个数元素复制到另一个数组中
举例:
假设在 scores 数组中保存了 8 名学生的成绩信息,现在需要复制该数组从第二个元素开始到结尾的所有元素到一个名称为 newScores 的数组中,长度为 12。scores 数组中的元素在 newScores 数组中从第三个元素开始排列。
使用 System.arraycopy() 方法来完成替换数组元素功能的代码如下:
public class TestArraycopy {
public static void main(String[] args) {
// 定义原数组,长度为8
int scores[] = new int[] { 100, 81, 68, 75, 91, 66, 75, 100 };
// 定义目标数组
int newScores[] = new int[] { 80, 82, 71, 92, 68, 71, 87, 88, 81, 79, 90, 77 };
System.out.println("原数组中的内容如下:");
// 遍历原数组
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + "\t");
}
System.out.println("\n目标数组中的内容如下:");
// 遍历目标数组
for (int j = 0; j < newScores.length; j++) {
System.out.print(newScores[j] + "\t");
}
System.arraycopy(scores, 0, newScores, 2, 8);
// 复制原数组中的一部分到目标数组中
System.out.println("\n替换元素后的目标数组内容如下:");
// 循环遍历替换后的数组
for (int k = 0; k < newScores.length; k++) {
System.out.print(newScores[k] + "\t");
}
}
}
在该程序中,首先定义了一个包含有 8 个元素的 scores 数组,接着又定义了一个包含有 12 个元素的 newScores 数组,然后使用 for 循环分别遍历这两个数组,输出数组中的元素。最后使用 System.arraycopy() 方法将 newScores 数组中从第三个元素开始往后的 8 个元素替换为 scores 数组中的 8 个元素值。
该程序运行的结果如下所示。
原数组中的内容如下:
100 81 68 75 91 66 75 100
目标数组中的内容如下:
80 82 71 92 68 71 87 88 81 79 90 77
替换元素后的目标数组内容如下:
80 82 100 81 68 75 91 66 75 100 90 77