45 System.out.print( arr[j] + \" \"); 46 System.out.println(\"\"); 47 } 48 }下面代码用面向对象的方法实现,看看这两者的区别 代码如下
1 class LowArray 2 {
3 private long[] a; // ref to array a
4 //-------------------------------------------------------------- 5 public LowArray(int size) // constructor 6 { a = new long[size]; } // create array
7 //-------------------------------------------------------------- 8 public void setElem(int index, long value) // set value 9 { a[index] = value; }
10 //-------------------------------------------------------------- 11 public long getElem(int index) // get value 12 { return a[index]; }
13 //-------------------------------------------------------------- 14 }
15 //////////////////////////////////////////////////////////////// 16 class LowArrayApp 17 {
18 public static void main(String[] args) 19 {
20 LowArray arr; // reference
21 arr = new LowArray(100); // create LowArray object 22 int nElems = 0; // number of items in array 23 int j; // loop variable 24
25 arr.setElem(0, 77); // insert 10 items 26 arr.setElem(1, 99); 27 arr.setElem(2, 44); 28 arr.setElem(3, 55); 29 arr.setElem(4, 22); 30 arr.setElem(5, 88); 31 arr.setElem(6, 11);
32 arr.setElem(7, 00); 33 arr.setElem(8, 66); 34 arr.setElem(9, 33);
35 nElems = 10; // now 10 items in array 36
37 for(j=0; j41 int searchKey = 26; // search for data item 42 for(j=0; j45 if(j == nElems) // no46 System.out.println(\"Can't find \" + searchKey); 47 else // yes
48 System.out.println(\"Found \" + searchKey); 49
50 // delete value 55 51 for(j=0; j54 for(int k=j; k56 nElems--; // decrement size 5758 for(j=0; j62 } // end class LowArrayApp