java实现数组的增删改查


难点1.删除之后如何更改数组下标
数组下标无法更改,此处巧妙使用api中Arrays.copeof:

java.util.Arrays.copyOf(T[] original, int newLength) 方法复制指定的数组,截取或用null填充(如有必要),以使副本具有指定的长度。对于这一切都有效同时在原数组和副本索引,这两个数组将包含相同的值。对于在副本中有效,但不是原来的任何索引,副本将包含null。这些索引存在,当且仅当指定长度大于原数组。结果数组是完全一样的类作为原始数组的。



难点2:数组越界之后能使其可以重新输入
方法:设置标志


此代码为练习代码,先为数组定义下表然后赋值,进行增删改查操作



import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class TestArray { public static void main(String[] args) { int[] array; int subscript, key,temp; ; Scanner in = new Scanner(System.in); System.out.println("input subscript :"); subscript = in.nextInt(); //下标 array = new int[subscript]; //assignment System.out.println("assignment please"); assignment(array); System.out.println("---------------"); System.out.println(Arrays.toString(array)); //modify System.out.println("modify please :"); key = in.nextInt(); temp = in.nextInt(); boolean b = true; while(b){ if(key>=array.length){ System.out.println("array out of range,input again"); key = in.nextInt(); }else{ b = false; } } modify(array,key,temp); System.out.println("---------------"); System.out.println(Arrays.toString(array)); //delete System.out.println("input delete number please"); temp = in.nextInt(); delete(array,temp); System.out.println("---------------"); array=Arrays.copyOf(array, array.length-1); System.out.println(Arrays.toString(array)); //add System.out.println("input add number please"); temp = in.nextInt(); System.out.println("---------------"); array=Arrays.copyOf(array, array.length+1); add(array,temp); System.out.println(Arrays.toString(array)); //querry System.out.println("input querry number please"); temp = in.nextInt(); System.out.println("---------------"); System.out.println(querry(array,temp)); } private static int querry(int[] array, int temp) { // TODO Auto-generated method stub int i; for ( i = 0; i < array.length; i++) { if(array[i]==temp){ break; } } return i; } private static void add(int[] array, int temp) { // TODO Auto-generated method stub array[array.length-1]=temp; } private static void delete(int[] array, int temp) { // TODO Auto-generated method stub int i; for (i = 0; i < array.length; i++) { if(array[i]==temp) break; } for(int j=i; j


【java实现数组的增删改查】

    推荐阅读