一.高级接口数组类的设计与实现:
a.数组类的设计
- //highArray.java
- //the definition of Array class with high-level interface
- /
- public class highArray {
- private long[]a;//ref to array a
- private int nElems;//number of array data items
- //---------------------------------------------------
- public highArray(int nax)//construtor
- {
- a=new long[nax];//creat the array,declaration
- nElems=0;//there is no items yet
- }
- //...................................................
- public boolean find(long searchKey)//find the specified value
- {
- int j;
- for(j=0;j<nElems;j++)
- {
- if(a[j]==searchKey)
- break;//found it and jump out of the loop
- }
- if (j==nElems)return false;//not found
- else return true;
- }
- //...................................................
- public void insert(long value)//put element into array
- {
- a[nElems]=value;//put the value into the array
- nElems++;//add the total number of the data items
- }
- public boolean delete(long value)//delete an array item
- {
- int j,k;
- for(j=0;j<nElems;j++)//search the item
- {
- if(a[j]==value)
- break;
- }
- if(j==nElems)return false;//not found
- else
- {
- for(k=j;k<nElems;k++)//put every item behind the target one ahead
- {
- a[k]=a[k+1];
- }
- nElems--;
- return true;
- }
- }
- public void display()
- {
- for(int j=0;j<nElems;j++)
- {
- System.out.println(a[j]+" ");
- }
- //....................................................................
- }
- }
b.主函数类
- public class HighArrayApp {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int maxSize=100;
- highArray arr;
- arr=new highArray(maxSize);//初始化
- arr.insert(77);
- arr.insert(99);
- arr.insert(44);
- arr.insert(55);
- arr.insert(22);
- arr.insert(16);
- arr.insert(33);
- arr.insert(56);
- arr.insert(33);
- arr.display(); //display items
- int searchKey=44;
- if(arr.find(searchKey))
- System.out.println("Found"+searchKey);
- else
- System.out.println("Can't find"+searchKey);
- arr.delete(22);
- arr.delete(56);
- arr.delete(55);
- arr.display();
- }
- }
c.输出结果
- 77
- 99
- 44
- 55
- 22
- 16
- 33
- 56
- 33
- Found44
- 77
- 99
- 44
- 16
- 33
- 33