您好,欢迎来到华拓科技网。
搜索
您的当前位置:首页java数组举例

java数组举例

来源:华拓科技网
这个例子是用面向过程的编写,然后再介绍一个可达到同样效果的面向对象的方法 array.java代码如下:

1 class ArrayApp 2 {

3 public static void main(String[] args) 4 {

5 long[] arr; //声明数组 6 arr = new long[100]; // 创建数组 7 int nElems = 0; // 索引 8 int j; // 循环变量 9 long searchKey; //关键字

10 //-------------------------------------------------------------- 11 arr[0] = 77; //插入十项 12 arr[1] = 99; 13 arr[2] = 44; 14 arr[3] = 55; 15 arr[4] = 22; 16 arr[5] = 88; 17 arr[6] = 11; 18 arr[7] = 00; 19 arr[8] = 66; 20 arr[9] = 33;

21 nElems = 10; // 索引值为10

22 //-------------------------------------------------------------- 23 for(j=0; j26 //-------------------------------------------------------------- 27 searchKey = 66; //查找值为 66 28 for(j=0; j32 System.out.println(\"Can't find \" + searchKey); 33 else

34 System.out.println(\"Found \" + searchKey);

35 //-------------------------------------------------------------- 36 searchKey = 55; //删除55 37 for(j=0; j40 for(int k=j; k41 arr[k] = arr[k+1];

42 nElems--;

43 //-------------------------------------------------------------- 44 for(j=0; j45 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) // no

46 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 57

58 for(j=0; j62 } // end class LowArrayApp

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo6.cn 版权所有 赣ICP备2024042791号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务