1 // LowArrayApp.java 2 // demonstrates array class with low-level interface 3 // to run this program: C>java LowArrayAPP 4 //java数据结构和算法(第二版)拉佛 著 pdf第46页 数组操作 5 6 package first; 7 8 class LowArray 9 {10 private long[] a; // ref to array a11 12 public LowArray(int size) // constructor13 { a = new long[size]; } // create array14 15 public void setElem(int index, long value) // set value16 { a[index] = value; }17 18 public long getElem(int index) // get value19 { return a[index]; }20 21 } // end class LowArray22 23 24 public class LowArrayAPP 25 {26 public static void main(String[] args)27 {28 LowArray arr; // reference29 arr = new LowArray(100); //create LowArray object30 int nElems = 0; // number of items in array31 int j; // loop variable32 33 arr.setElem(0, 77);34 arr.setElem(1, 99);35 arr.setElem(2, 44);36 arr.setElem(3, 55);37 arr.setElem(4, 22);38 arr.setElem(5, 88);39 arr.setElem(6, 11);40 arr.setElem(7, 00);41 arr.setElem(8, 66);42 arr.setElem(9, 33);43 nElems = 10; // now 10 items in array44 45 // display items46 for (j = 0; j < nElems; j++) 47 System.out.print(arr.getElem(j) + " ");48 System.out.println("");49 50 //search for data item51 int searchKey = 26;52 for(j=0; j < nElems; j++)53 if(arr.getElem(j) == searchKey)54 break;55 if(j == nElems)56 System.out.println("Can't find " + searchKey);57 else58 System.out.println("Found " + searchKey);59 60 //delete value 5561 for(j = 0; j < nElems; j++)62 if (arr.getElem(j) == 55)63 break;64 65 for(int k = j; k < nElems; k++) // 删掉的数据项后面所有单元逐个前移一位66 arr.setElem(k, arr.getElem(k+1));67 nElems--;68 69 // display items70 for (j = 0; j < nElems; j++) 71 System.out.print(arr.getElem(j) + " ");72 System.out.println("");73 74 } // end main()75 } // end class LowArrayAPP 运行结果:
77 99 44 55 22 88 11 0 66 33 Can't find 2677 99 44 22 88 11 0 66 33