Java 集合框架之 Stack
简介
java.util.Stack
降生于jdk1.0
。
继承自java.util.Vector
,所以从jdk1.2
开始,也是集合框架中的一员,归属于List
这个子类。
这个类已经不太推荐使用,优先使用java.util.Deque
的实现。
优先使用java.util.Deque
的原因:
- 因为这个类是
java.util.Vector
,而且拓展的几个方法也是线程安全的,所以这个类是线程安全的,都是性能也会相对较差。 - 接口没有
java.util.Deque
完善 - 各种设计感觉有缺陷:
java.util.Vector
。
源码解析
源码基于JDK 1.8u201
。
由于java.util.Stack
中的方法基于java.util.Vector
,这篇文章不做详细解说,详情查看 Vector 源码解析。
入栈 todo
/**
* Pushes an item onto the top of this stack. This has exactly
* the same effect as:
* <blockquote><pre>
* addElement(item)</pre></blockquote>
*
* @param item the item to be pushed onto this stack.
* @return the <code>item</code> argument.
* @see java.util.Vector#addElement
*/
public E push(E item) {
addElement(item);
return item;
}
入栈操作是将元素插入到尾端。
出栈 todo
/**
* Removes the object at the top of this stack and returns that
* object as the value of this function.
*
* @return The object at the top of this stack (the last item
* of the <tt>Vector</tt> object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
出栈操作是读取尾端元素,然后移除。
查看栈顶元素
/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack (the last item
* of the <tt>Vector</tt> object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
这个方法只是查看尾端元素,而不移除。
需要注意的是:如果为空栈时,会抛出java.util.EmptyStackException
异常,所以记得先判断是否为空栈或者捕捉异常。