在此之前已經(jīng)在本書中介紹過數(shù)組了。現(xiàn)在既然你已了解了類,可以介紹關(guān)于數(shù)組的重要的一點(diǎn):數(shù)組是作為對象來實(shí)現(xiàn)的。因此,你可能想要利用數(shù)組的一種非凡的屬性,具體地說,就是一個數(shù)組的大小——也就是,一個數(shù)組能保存的元素的數(shù)目——可以在它的length 實(shí)例變量中找到。所有的數(shù)組都有這個變量,并且它總是保存數(shù)組的大小。下面的程序示例了這個性質(zhì):
// This PRogram demonstrates the length array member.
class Length {
public static void main(String args[]) { int a1[] = new int[10];int a2[] = {3,5,7,1,8,99,44,-10};int a3[] = {4,3,2,1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}
該程序顯示如下輸出:
length of a1 is 10
length of a2 is 8
length of a3 is 4
可以看出,每個數(shù)組的大小都被顯示。要記住length 的值和數(shù)組實(shí)際使用的元素的個數(shù)沒有關(guān)系。length 僅反映了數(shù)組能夠包含的元素的數(shù)目。
在許多情況下,你可以好好利用length 。例如,下面的程序是Stack類的改進(jìn)版本。你可能回憶起,該類的早期的版本總是要產(chǎn)生一個10個元素的堆棧。下面的版本可以讓你產(chǎn)生任意長度的堆棧。stck.length 的值用來防止堆棧溢出。
// Improved Stack class that uses the length array member.
class Stack { private int stck[]; private int tos;
// allocate and initialize stack
Stack(int size) {
stck = new int[size];
tos = -1;
新聞熱點(diǎn)
疑難解答