package stack;
public interface IStack<T> {
public T pop();
public void push(T elem);
public T peek();
public boolean isEmpty();
public void clean();
}
package stack;
import java.util.Arrays;
public class ArrayStack<T> implements IStack<T> {
private final int DEFAULT_SIZE = 3;
private int size = 0;
private int capacity = 0;
private int top = 0;
private Object[] array;
public ArrayStack(){
this.capacity = DEFAULT_SIZE;
this.array = new Object[this.capacity];
this.size = 0;
}
public ArrayStack(int capacity){
this.capacity = capacity;
this.array = new Object[this.capacity];
this.size = 0;
}
@SuppressWarnings("unchecked")
@Override
public T pop() {
T elem = (T)this.array[top-1];
this.array[top-1]=null;
this.size--;
return elem;
}
@Override
public void push(T elem) {
if(this.size<this.capacity){
this.array[top]=elem;
this.top++;
this.size++;
}else{
enlarge();
push(elem);
}
}
public void enlarge() {
this.capacity = this.capacity+this.DEFAULT_SIZE;
Object[] newArray = new Object[this.capacity];
System.arraycopy(array, 0, newArray, 0, array.length);
Arrays.fill(array, null);
this.array = newArray;
}
@SuppressWarnings("unchecked")
@Override
public T peek() {
return (T)this.array[top-1];
}
@Override
public boolean isEmpty() {
return size==0;
}
@Override
public void clean() {
Arrays.fill(array, null);
this.top = 0;
this.size=0;
this.capacity = this.DEFAULT_SIZE;
this.array = new Object[this.capacity];
}
public int size(){
return this.size;
}
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<Integer>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.isEmpty());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.size());
stack.clean();
System.out.println(stack.size());
}
}