闲言碎语不多讲,上代码
注意 ensureCapacity 方法
import java.util.Arrays;
public class StackDemo {
private Object[] array;
private int elementCount;
private StackDemo(){
this(10);
elementCount = 0;
}
private StackDemo(int size){
array = new Object[size];
}
public boolean empty(){
return (elementCount == 0);
}
public Object peek(){
if(empty())
return null;
Object o = array[elementCount -1];
return o;
}
public Object pop(){
if(empty()){
System.out.println("--Stack is empty.");
return null;
}
Object o = peek();
elementCount --;
array[elementCount] = null; //to let gc work.
return o;
}
public void push(Object o){
ensureCapacity(elementCount + 1);
array[elementCount++] = o;
}
private void ensureCapacity(int minCapacity){
int oldCapacity = array.length;
if(minCapacity > oldCapacity){
int newCapacity = oldCapacity * 2;
if(newCapacity < minCapacity)
newCapacity = minCapacity;
//复制指定的数组 长度为newCapacity
array = Arrays.copyOf(array, newCapacity);
}
}
public static void main(String[] args){
StackDemo stack = new StackDemo();
for(int i=0; i<33; i++){
stack.push(i + 1);
}
for(int i=0; i<35; i++){
Integer n = (Integer)stack.pop();
System.out.println("Object value-->" + n);
}
}
}