在此程序中,HighArray类中的find()方法用数据项的值作为参数传递,它的返回值决定是否找到此数据项。
insert()方法向数组下一个空位置放置一个新的数据项。一个名为nElems的字段跟踪记录着数组中的数据项个数。
根据以参数形式传入的关键字,delete()方法查找相应的数据项。当他找到该数据项后,便将该所有后面的数据项前移,从而将此数据项覆盖,达到删除的目的。
在这个程序中,类用户HighArrayAPP不用考虑数组的下标,因为结构被隐藏,所以也不用考虑HighArray中使用何种数据结构来存储数据。
main方法非常简洁。
class HighArray {
private long[] a;
private int nElems;
// constructor
public HighArray(int max) {
a = new long[max];
nElems = 0;
}
// find specified value
public boolean find(long searchKey) {
int j;
for(j=0; j<nElems; j++) {
if(a[j] == searchKey) {
break;
}
}
if(j == nElems) {
return false;
}
else {
return true;
}
} // end find()
// put element into array
public void insert(long value) {
a[nElems] = value;
nElems++;
}
// delete specified value
public boolean delete(long value) {
int j;
for(j=0; j<nElems; j++) { // look for it
if(value == a[j]) {
break;
}
}
if(j == nElems) {
return false; // can't find it
}
else {
for(int k=j; k<nElems; k++) {
a[k] = a[k+1]; // move higher ones down
}
nElems--;
return true;
}
} // end delete()
// display items
public void display() {
for(int j=0; j<nElems; j++) {
System.out.print(a[j] + " ");
}
System.out.println("");
} // end display()
} // end class HighArray
class HighArrayApp {
public static void main(String[] args) {
int maxSize = 100;
HighArray arr;
arr = new HighArray(maxSize);
// insert 10 items
arr.insert(77);
arr.insert(99);
arr.insert(44);
arr.insert(55);
arr.insert(22);
arr.insert(88);
arr.insert(11);
arr.insert(00);
arr.insert(66);
arr.insert(33);
// display items
arr.display();
// search for item 35
int searchKey = 35;
if(arr.find(searchKey)) {
System.out.println("Found " + searchKey);
}
else {
System.out.println("Can't find " + searchKey);
}
// delete 3 items
arr.delete(00);
arr.delete(55);
arr.delete(99);
// display items
arr.display();
} // end main()
} // end class HighArrayApp
77 99 44 55 22 88 11 0 66 33
Can't find 35
77 44 22 88 11 66 33