package testJava;
import java.util.Arrays;
public class MyStack<T> {
//设置栈的默认大小
private static int DEFAULT_SIZE=3;
//当前栈中的元首
private int size=0;
//每次需要扩展的容量
private int capacity=0;
//永远指向可添加元素的位置
private int index=0;
private Object[] array;
public MyStack(){
this.capacity=this.DEFAULT_SIZE;
array=new Object[this.capacity];
}
//自定义栈大小
public MyStack(int capacity){
this.capacity=capacity;
array=new Object[this.capacity];
}
//判断栈是否为空
public boolean isEmpty() {
return size==0;
}
//查看栈顶元素,并不出栈
public T peek() {
return (T)this.array[this.index-1];
}
//出栈
public T pop() {
index--;
T t= (T)this.array[this.index];
this.array[this.index]=null;
this.size--;
return t;
}
//压栈
public void push(T t) {
if (this.size<this.capacity) {
this.array[this.index]=t;
this.index++;
this.size++;
}else {
enlarge();
this.array[this.index]=t;
this.index++;
this.size++;
}
}
//扩充容量,然后把原始数据复制到新数组中,然后再赋值回array数组
public void enlarge(){
System.out.println("enlarge----");
//设置新数组扩充的大小
this.capacity=this.capacity+this.DEFAULT_SIZE;
Object[] temp=new Object[this.capacity];
//把原始数据复制到新的数组中
System.arraycopy(array, 0, temp, 0, array.length);
//清空原始数据的值
Arrays.fill(array, null);
//把新的数组再赋值回原始数组
this.array=temp;
}
//清空栈数据,让数组成为初始状态
public void clear(){
Arrays.fill(array, null);
this.index=0;
this.size=0;
this.capacity=this.DEFAULT_SIZE;
//重新创建一个数组
array=new Object[this.capacity];
}
//计算当前的元素个数
public int count() {
return this.size;
}
public static void main(String[] args) {
MyStack<String> myStack = new MyStack<String>();
System.out.println("判断数组是否为空:"+myStack.isEmpty());
myStack.push("a");
myStack.push("b");
myStack.push("c");
System.out.println("判断数组的元素数量:"+myStack.count());
System.out.println("查看栈顶的元素:"+myStack.peek());
System.out.println("判断数组的元素数量:"+myStack.count());
myStack.push("d");
System.out.println("判断数组的元素数量:"+myStack.count());
System.out.println("出栈操作:"+myStack.pop());
System.out.println("出栈操作:"+myStack.pop());
System.out.println("出栈操作:"+myStack.pop());
System.out.println("出栈操作:"+myStack.pop());
System.out.println("判断数组是否为空:"+myStack.isEmpty());
myStack.clear();
System.out.println("this.size="+myStack.count()+","+"this.capacity="+myStack.capacity);
}
}