直接上代码吧
import java.util.Arrays;
public class MyStack<E> {
private static final int INIT_CAPACITY=6;//初始化容量
private Object[] elements;
private int index=0;//栈顶指针 指向栈顶的空元素的位置
private boolean canGrow=true;//是否可以扩容
public MyStack(boolean canGrow) {
super();
this.canGrow = canGrow;
elements=new Object[INIT_CAPACITY];
}
public MyStack(boolean canGrow,int capacity) {
super();
this.canGrow = canGrow;
elements=new Object[capacity];
}
/**
* 获取集合的个数
* @return
*/
public int size(){
return index;
}
/**
* 获取集合的容量
* @return
*/
public int capacity(){
return elements.length;
}
/**
* 获取栈顶元素
* @return
*/
public E peek(){
if(isEmpty()){
return null;
}else{
return (E) elements[index];
}
}
/**
* 弹栈
* @return
*/
public E pop(){
//判空
if(isEmpty()){
return null;
}else{
index--;
E element=(E) elements[index];
elements[index]=null;//弹栈后置空,方便回收
return element;
}
}
private boolean isEmpty() {
return index==0;
}
/**
* 压栈
* @param e
* @return
*/
public boolean push(E e){
if(isFull()){
if(canGrow){
//扩容规则为:原有容量的1.5倍
Object[] newElements=new Object[index+index/2];
System.arraycopy(elements, 0, newElements, 0, index);
elements=newElements;
elements[index++]=e;
}else{
try {
//栈满后抛出异常
throw new Exception("栈满了!");
} catch (Exception e1) {
e1.printStackTrace();
}
return false;
}
}else{
elements[index++]=e;
}
return true;
}
private boolean isFull() {
return index>=elements.length;
}
@Override
public String toString() {
//将现有元素copy到一个新数组,用于去掉null
Object[] o=new Object[index];
System.arraycopy(elements, 0, o, 0, index);
return Arrays.toString(o);
}
public void clear(){
if(isEmpty()){
return;
}else{
//清空操作之前将元素值置空,方便回收
for(int i=0;i<elements.length;i++){
elements[i]=null;
}
index=0;
}
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyStack<E> other = (MyStack) obj;
if (canGrow != other.canGrow)
return false;
if (!Arrays.equals(elements, other.elements))
return false;
if (index != other.index)
return false;
return true;
}
}