private static final int INITIAL_CAPACITY = 15;
private Object[] elements;
private int length;
private int capacity;
public ArrayStack() {
this(INITIAL_CAPACITY);
}
public ArrayStack(int capacity) {
elements = new Object[capacity];
this.capacity = capacity;
}
@SuppressWarnings("unchecked")
@Override
public T pop() {
if (length <= 0) {
throw new NoSuchElementException("栈为空,没有元素");
}
T t = (T) elements[--length];
System.out.println("出栈:" + t.toString());
return t;
}
@Override
public boolean push(T t) {
if (!checkBound()) {
throw new ArrayIndexOutOfBoundsException(checkBoundMessage());
}
@SuppressWarnings("unchecked")
@Override
public T peek() {
if (length <= 0) {
throw new NoSuchElementException("栈为空,没有元素");
}
T t = (T) elements[length - 1];
System.out.println("获得栈顶元素:" + t.toString());
return t;
}
@Override
public boolean isEmpty() {
return length == 0;
}
@Override
public int getIndex(Object obj) {
for (int i = 0; i < length; i++) {
if (elements[i].equals(obj)) {
System.out.println("找到索引是:" + i);
return i;
}
}
throw new NoSuchElementException("未找到元素:" + obj.toString());
}
@Override
public int length() {
System.out.println("length = " + length);
return length;
}
public String travers() {
if (isEmpty()) {
return null;
}