Summary:
- public class Stack<E> extends Vector<E>
- Stack主要使用的是Vector<E>的方法进行具体的实现,自身没有状态量
- 因为是继承Vector故它也是线程安全的
- pop方法使用peek+removeElementAt
- peek方法使用elementAt
- push方法使用addElement
- search方法从后往前搜索调用lastIndexOf
Fields:
无
Constructor:
//默认构造一个空栈
public Stack() {
}
push():
//调用父类vector的addElement方法,即将数据加到数组的末尾
public E push(E item) {
addElement(item);
return item;
}
pop():
//调用自身的peek方法
//接着调用父类vector的removeElementAt方法移除数组中的最后一个元素
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
peek():
//调用父类vector的elementAt,返回数组最末的数据
//这里之所以不直接使用vector的lastElement():方法,是因为它想抛出EmptyStackException();
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
empty():
//调用父类的size()返回当前数组中存储数据的大小
//而非容量大小,容量大小使用capacity
public boolean empty() {
return size() == 0;
}
search():
//从后往前搜索
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}