您的位置:首页 > 编程语言 > Java开发

由数组的封装来浅谈JAVA面向对象的思路

2009-05-29 19:49 567 查看
//demonstrates Java arrays
//基本操作:创建一个数组(插入),查找、删除数据项,显示。
class ArrayApp {
public static void main(String[] args) {
long[] arr; // reference to array
arr = new long[100]; // make array
int nElems = 0; // number of items
int j; // loop counter
long searchKey; // key of item to search for
arr[0] = 77; // insert 10 items
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;
nElems = 10; // now 10 items in array
for (j = 0; j < nElems; j++)
System.out.print(arr[j] + " ");
System.out.println("");
searchKey = 66; // find item with key 66
for (j = 0; j < nElems; j++)
if (arr[j] == searchKey) // found item?
break; // yes, exit before end
if (j == nElems) // at the end?
System.out.println("Can't find " + searchKey); // yes
else
System.out.println("Found " + searchKey); // no
searchKey = 55; // delete item with key 55
for (j = 0; j < nElems; j++)
// look for it
if (arr[j] == searchKey)
break;
for (int k = j; k < nElems; k++)
// move higher ones down
arr[k] = arr[k + 1];
nElems--; // decrement size
for (j = 0; j < nElems; j++)
// display items
System.out.print(arr[j] + " ");
System.out.println("");
} // end main()
} // end class ArrayApp

将普通的Java数组封装在HighArray类中,从而使数组隐藏起来,属性是私有的,外部无法访问,只提供接口(方法)。类的用户HighArrayApp通过类接口与类相连。
//demonstrates array class with high-level interface
//基本操作:创建一个数组(插入),查找、删除数据项,显示。
class HighArray {
private long[] a; // ref to array a
private int nElems; // number of data items
public HighArray(int maxSize) {
a = new long[maxSize];
nElems = 0;
}
public void insert(long value) {
a[nElems] = value;
nElems ++;
}
public void display() {
for(int j=0; j<nElems; j++)
System.out.print(a[j] + " ");
System.out.println();
}
public void find(long searchKey) {
int j;
for(j=0; j<nElems; j++)
if(j == searchKey)
break;
if(j == nElems) {
System.out.println("Can't find " + searchKey);
}
else System.out.println("Can find " + searchKey);
}
public void delete(long value) {
int j;
for(j=0; j<nElems; j++)
if(a[j] == value)
break;
if(j == nElems) {
System.out.println(value + " isn't in array, Can't delet.");
}
else {
System.out.println(value + " is in array.");
for(int k=j; k<nElems; k++)
a[k] = a[k+1];
nElems --;
}
}
} // end class HighArray

class HighArrayApp {
public static void main(String[] args) {
int maxSize = 100; // array size
HighArray arr; // reference to array
arr = new HighArray(maxSize); // create the array
arr.insert(77); // insert 10 items
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);
arr.display(); // display items
arr.find(35);
arr.delete(00); // delete 3 items
arr.delete(55);
arr.delete(99);
arr.display(); // display items again
} // end main()
} // end class HighArrayApp
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: