classHighArray{ privatelong[] data; //ref to array data privateint size; //number of data items publicHighArray(int max){ //constructor data = newlong[max]; //creat the array size = 0; //no items yet } publicbooleanfind(long searchKey){ //find specified value int j; for(j=0;j<nElems;j++){ //for each elements if(data[j] == searchKey) //found items? break; //exit loop before end gone to end? } if(j == size) returnfalse; //can't found it else returntrue; // found it } publicvoidinsert(long value){ //put elements into array data[size] = value; //insert it nElems ++; //increamnt size } publicbooleandelete(long value){ int j; for (j=0 ;j<size ;j++) //look for it if(value == a[j]) break; if(j == size) returnfalse; //can't find it else for(int k=j;k< size;k++) a[k] = a[k+1]; //move higher ones down size--; //decrement size returntrue; } publicvoiddisplay(){ for(int j =0;j<nElems;j++) //for each elements System.out.println(a[j]+" "); //display for it } }
add(int index,int e) 方法:把元素添加到指定位置。
1、先判断index是否越界,若越界则抛出异常。
2、如果数组元素个数与长度相等,则需要扩容。
3、通过循环,把数组中从最后一位到index位置的元素都向后挪动一位
4,再把index位置中的元素赋值成e。元素数量增加
1 2 3 4 5 6 7 8 9 10 11 12 13
publicvoidadd(int index,int e){ //先判断index是否越界 if(index < 0|| index> size) thrownew IllegalArgumentException("Add failed. Require index >= 0 and index <= size."); //如果数组元素个数与长度相等,需要扩容 if(size == data.length) resize(2*data.length); //把数组中从最后到index位置的元素都向后挪动一位,再把index位置中的元素赋值成e for(int i = size; i >= index ;i--) data[i+1] = data[i]; data[index] = e; size++; }