public class Stack<T> {
private int top = -1;
private int stackSize = 0;
private T[] stack = null;
Stack(int stackSize) {
this.stackSize = stackSize;
stack = (T[]) new Object[stackSize];
}
public void push(T t) {
if (top < stackSize - 1) {
stack[++top] = t;
System.out.println("Success push into the stack, the elemetn is " + t + ".");
} else {
System.out.println("Sorry,can't push into the stack! The stack is full.");
}
}
public T pop() {
if (!isEmpty()) {
return stack[top--];
} else {
System.out.println("Sorry,the stack is empty.");
return null;
}
}
public int size() {
return top + 1;
}
public boolean isFull() {
return stackSize == top + 1;
}
public boolean isEmpty() {
return top == -1;
}
public static void main(String[] args) {
Stack<String> stringStack = new Stack<>(5);
for (int i = 0; i < 10; i++) {
stringStack.push("str" + i);
}
System.out.println("The stack's size is " + stringStack.size() + ".");
System.out.println("is full: " + stringStack.isFull());
System.out.println("is empty: " + stringStack.isEmpty());
for (int i = 0; i < 5; i++) {
System.out.println("Stack pop a element, it is " + stringStack.pop() + ".");
}
}
}