服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

重新温习数组

在此之前已经在本书中介绍过数组了。现在既然你已了解了类,可以介绍关于数组的重要的一点:数组是作为对象来实现的。因此,你可能想要利用数组的一种特别的属性,具体地说,就是一个数组的大小――也就是,一个数组能保存的元素的数目――可以在它的length 实例变量中找到。所有的数组都有这个变量,并且它总是保存数组的大小。下面的程序示例了这个性质:

// 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

可以看出,每个数组的大小都被显示。要记住length 的值和数组实际使用的元素的个数没有关系。length 仅反映了数组能够包含的元素的数目。

在许多情况下,你可以好好利用length 。例如,下面的程序是stack类的改进版本。你可能回忆起,该类的早期的版本总是要产生一个10个元素的堆栈。下面的版本可以让你产生任意长度的堆栈。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;

}

// push an item onto the stack void push(int item) {if(tos==stck.length-1) // use length member system.out.println("stack is full.");
else
stck[++tos] = item;
}

// pop an item from the stack int pop() {

if(tos < 0) { system.out.println("stack underflow."); return 0;

}
else
return stck[tos--];
}
}

class teststack2 {

public static void main(string args[]) {
stack mystack1 = new stack(5);
stack mystack2 = new stack(8);
// push some numbers onto the stack
for(int i=0; i<5; i++) mystack1.push(i);
for(int i=0; i<8; i++) mystack2.push(i);

// pop those numbers off the stack
system.out.println("stack in mystack1:");
for(int i=0; i<5; i++)

system.out.println(mystack1.pop());

system.out.println("stack in mystack2:");
for(int i=0; i<8; i++)
system.out.println(mystack2.pop());
}
}

注意,该程序创建了两个堆栈:一个有5个元素,另一个有8个元素。可以看出,数组保持它们自己长度信息的事实使创建任何大小的堆栈很容易。

扫描关注微信公众号