java|java 动态实现数组增删(韩顺平)

一.简单的数组扩容

int[] arr1 = {1,2,3}; int[] arrNew = new int[arr1.length + 1]; for (int i = 0; i < arr1.length; i++) { arrNew[i] = arr1[i]; } arrNew[arr1.length] = 5; arr1 = arrNew; //将arrnew的地址传给arr1后,数组arr1将消失 for (int i = 0; i < arr1.length + 1; i++) { System.out.println(arrNew[i]); } for (int i = 0; i < arr1.length; i++) { System.out.println(arr1[i]); }

二.连续进行数组扩容
不知道用户什么时候结束扩容,用do-while + break语句来实现
Scanner myscanner = new Scanner(System.in); int[] arr = {1,2,3}; do { int[] arrnew = new int[arr.length + 1]; for (int i = 0; i < arr.length; i++) { arrnew[i] = arr[i]; }arrnew[arrnew.length - 1] = myscanner.nextInt(); arr = arrnew; for (int i = 0; i < arrnew.length; i++) { System.out.println(arrnew[i]); }System.out.println("是否继续输入"); char key = myscanner.next().charAt(0); if (key == 'n') break; //输入n结束扩容 }while (true);

三.数组删减
int[] arr = {1,2,3}; Scanner myscanner = new Scanner(System.in); do {int[] newarr = new int[arr.length - 1]; for (int i = 0; i < newarr.length; i++) { newarr[i] = arr[i]; }arr = newarr; char s = myscanner.next().charAt(0); if (newarr.length == 0 || s == 'n') break; //输入n或数组大小为0时结束缩减for (int i = 0; i < newarr.length; i++) { System.out.println(newarr[i]); }}while (true);

【java|java 动态实现数组增删(韩顺平)】

    推荐阅读