数组的length成员
数组的大小即数组能够包含的元素的数量,包含在实例变量length中。所有数组都具有这个属性,并且它总是包含数组的大小。下面的程序演示了这个变量。
//This program demonstrates the length array member
public 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的值与实际使用的元素数量没有任何关系,它只反映在最初设计时数组所能包含的元素数量。
下面的demo,利用stck.length的值来防止堆栈溢出:
//Improved Stack class that uses the length array member.
public 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--];
}
}
public static void main(String[] args) {
Stack stack1 = new Stack(5);
Stack stack2 = new Stack(8);
//push stack
for(int i=0;i<5;i++) stack1.push(i);
for(int i=0;i<10;i++) stack2.push(i);
//pop stack
System.out.println("Stack in stack1:");
for(int i=0;i<5;i++) System.out.println(stack1.pop());
System.out.println("Stack in stack2");
for(int i=0;i<8;i++) System.out.println(stack2.pop());
/*
输出结果:
Stack is full
Stack is full
Stack in stack1:
4
3
2
1
0
Stack in stack2
7
6
5
4
3
2
1
0
*/
}
}
该程序创建了两个堆栈:一个堆栈可以容纳5个元素,另一个可以容纳8个元素。数组维护他们自身的长度信息,从而使得创建任意大小的堆栈变得很容易。