数组的拷贝与扩容
拷贝
-
首先需要两个数组
-
需要知道从哪里拷贝到哪里,拷贝多长
//需求:从源数组里面拷贝第二个数组-第五个数组,到目标数组里面 public class ArrayCopyDemo { public static void main(String[] args) { //源数组 int[] ages = {14, 25, 36, 12, 13, 45, 46}; //源数组开始拷贝的位置 int srcPos = 2; //拷贝数组的长度 int index = 4; //目标数组 int[] newAges = new int[index]; //目标数组开始拷贝的位置 int destPos = 0; //拷贝数组 for (int i = srcPos; i < srcPos + index; i++) { newAges[destPos++] = ages[i]; // destPos++; } //遍历输出目标数组 for (int newAge : newAges) { System.out.println(newAge); } } }
扩容
单元素扩容
//需求:在源数组里面在扩容3个元素,到目标数组里面
public class ArrayExpansionDemo {
public static void main(String[] args) {
//源数组
int[] array = {14, 12 ,15 ,13 ,16};
//扩容后的长度
int index = 6;
//目标数组
int[] newArray = new int[index];
//目标数组当前位置
int destPos = 0;
//拷贝源数组
for (int i = 0; i < array.length; i++) {
newArray[destPos++] = array[i];
}
//扩容
newArray[index - 1 ] = 25;
newArray[index - 2 ] = 24;
newArray[index - 3 ] = 28;
for (int i : newArray) {
System.out.println(i);
}
}
}
多元素扩容
//需求:在源数组里面在扩容3个元素,到目标数组里面
public class ArrayExpansionDemo {
public static void main(String[] args) {
//源数组1
int[] array1 = {1 , 2, 3, 4, 5, 6};
//源数组2
int[] array2 = {7, 8, 9};
//源数组2的拷贝位置
int srcPos = array1.length;
//目标数组长度
int index = 9;
//目标数组
int[] newArray = new int[index];
//目标数组开始拷贝的位置
int destPos = 0;
//拷贝源数组1
for (int i = 0; i < array1.length; i++) {
newArray[destPos++] = array1[i];
}
//拷贝源数组2
for (int i = 0; i < array2.length; i++) {
newArray[srcPos++] = array2[i];
}
//遍历输出目标数组
for (int i : newArray) {
System.out.println(i);
}
}
}
标签:扩容,index,int,++,newArray,数组,拷贝
From: https://blog.51cto.com/u_16079786/8009276