package edu.basejava.util;
public class Stack<V>
{
private static final int defaultSize = 10;
private int size;
private int top;
private V[] value;
public Stack()
{
this.setup(Stack.defaultSize);
}
public Stack(int size)
{
this.setup(size);
}
public void push(V value)
{
if (this.isFull())
Log.error("栈容量已满");
else
{
this.value[this.top++] = value;
}
}
public V pop()
{
if (this.isEmpty())
return null;
else
return this.value[--this.top];
}
public V peek()
{
return this.topValue();
}
public V topValue()
{
if (this.isEmpty())
return null;
else
return this.value[this.top - 1];
}
public void clear()
{
this.top = 0;
for (@SuppressWarnings("unused")
V v : this.value)
v = null;
}
public boolean isEmpty()
{
return this.top == 0;
}
public boolean isFull() // true if stack is full
{
return (top == this.size);
}
@SuppressWarnings("unchecked")
private void setup(int size)
{
if (size < 0)
throw new IllegalArgumentException("错误的栈容量参数: " + size);
else
{
this.size = size;
this.value = (V[]) new Object[size];
}
}
}