数组拷贝操作 从数组默认下标 到拷到我指定的长度

来源:互联网 发布:c语言的编程环境 编辑:程序博客网 时间:2024/05/29 12:08
package com.heima.array;


public class AarryDemo3 {


public static void main(String[] args) {
/*
* 1.定义一个方法copyOf(int[] arr, int newLength),
* 功能:将数组arr中的newLength个元素拷贝到新数组中, 并将新数组返回, 从索引为0开始
*/


int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // 定义一个新的数组
getInfo(arr);// 遍历数组
arr = copyOf(arr, 5); // 给一个数组 给一个你要拷贝的长度 返回一个新的数组
System.out.println("拷贝后的数组是");
getInfo(arr);
}
       //拷贝数组元素
public static int[] copyOf(int[] arr, int newLength) {
int[] newarr = new int[newLength]; // 定义一个数组给
for (int i = 0; i < newLength; i++) { //循环从数组下标0拷贝到newLength这个下标为值
newarr[i] = arr[i]; //把原始数组中取出来放入新数组中进去
}
return newarr; //返回一个数组
}
      //遍历数组中的元素
public static void getInfo(int[] arr) {
for (int i : arr) {
if (i > 0) {
System.out.print(i + " ");
}
}
}
}
1 0
原创粉丝点击