需求:
Admin_Log
– 定义一个方法copyOfRange(int[] arr,int from,int to)
功能:
– 将数组arr中从索引from(包含from)开始。
– 到索引to结束(不包含to)的元素复制到新数组中
– 将新数组返回
package method;
public class arrDemo {
public static void main(String[] args) {
/*
需求:
- 定义一个方法copyOfRange(int[] arr,int from,int to)
功能:
- 将数组arr中从索引from(包含from)开始。
- 到索引to结束(不包含to)的元素复制到新数组中
- 将新数组返回
*/
// 1. 定义原始数组
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// 2. 调用方法拷贝数据
int[] copyArr = copyOfRange(arr, 3, 9);
// 3. 遍历数组打印数据
for (int i = 0; i < copyArr.length; i++) {
System.out.println(copyArr[i]);
}
}
//从数组arr中从索引from(包含from)开始。
//到索引to结束(不包含to)的元素复制到新数组中
public static int[] copyOfRange(int[] arr, int from, int to) {
// 1. 定义数组
// 动态数组:不知道所有元素,知道要存入几个元素
int[] newArr = new int[to - from];
// 2. 将原始数组arr中的form到to上对应的元素,拷贝到newArr中
// 伪造索引的思想 - 定义自增数据
int index = 0;
for (int i = from; i < to; i++) {
newArr[index] = arr[i];
index++;
}
// 3. 将新数组返回
return newArr;
}
}



