package com.zhb.corejava.util;
public class Stack {
private E[] elementData;
private int top;
private int count;
@SuppressWarnings("unchecked")
public Stack(int size) {
this.elementData = (E[]) new Object[size];
top = -1;
count = 0;
}
public Stack() {
this(10);
}
/**
* 返回堆栈长度
* @return
*/
public int getSize(){
return elementData.length;
}
/**
* 返回栈中元素的个数
* @return
*/
public int getElementCount() {
return count;
}
/**
* 判栈空
* @return
*/
public boolean isEmpty(){
return top == -1;
}
/**
* 判栈满
* @return
*/
public boolean isFull(){
return top == (elementData.length-1);
}
/**
* 入栈操作
* @param object
*/
public void push(E object){
if(isFull()){
throw new RuntimeException("栈已经满");
}else{
elementData[++top] = object;
count++;
}
}
/**
* 出栈操作,并返回被出栈的元素
* @return
*/
public E pop(){
if(isEmpty()){
throw new RuntimeException("栈是空的");
}else{
count--;
return elementData[top--];
}
}
/**
* 返回栈顶元素
* @return
*/
public E peek(){
if(isEmpty()){
throw new RuntimeException("栈是空的");
}else{
return elementData[top];
}
}
}
编写测试类:
package com.zhb.corejava.util;
public class ClientTest {
public static void main(String[] args) {
Stack stack = new Stack();
User user1 = new User("张三", 1);
User user2 = new User("李四", 2);
User user3 = new User("王五", 2);
stack.push(user1);
stack.push(user2);
stack.push(user3);
System.out.println("stack.size====" + stack.getSize());
User user = stack.pop();
System.out.println("user.name==1==" + user.getName());
System.out.println("-------------------------------------------");
user = stack.pop();
System.out.println("user.name==2==" + user.getName());
System.out.println("-------------------------------------------");
user = stack.pop();
System.out.println("user.name==3==" + user.getName());
System.out.println("stack.size====" + stack.getSize());
System.out.println("-------------------------------------------");
stack.push(user1);
System.out.println("stack.size====" + stack.getSize());
System.out.println("stack.isEmpty==="+stack.isEmpty());
System.out.println("stack.isFull==="+stack.isFull());
}
}