## 一、简介
![stack类图.png](http://upload-images.jianshu.io/upload_images/1541350-5fe08669097e7ac0.png?imagemogr2/auto-orient/strip%7cimageview2/2/w/1240)
栈是数据结构中一种很重要的数据结构类型,因为栈的后进先出功能是实际的开发中有很多的应用场景。java api中提供了栈(stacck)的实现。stack类继承了vector类,而vector类继承了abstractlist抽象类,实现了list类,cloneable接口,randomacces接口以及serializable接口。
## 二、源码阅读
#### 1.构造方法
```java
public stack() {
}
```
创建一个空栈。
#### 2.入栈push
public e push(e item) {
addelement(item);
return item;
public synchronized void addelement(e obj) {
modcount++;
ensurecapacityhelper(elementcount + 1);
elementdata[elementcount++] = obj;
入栈是一个同步的方法,调用vector的**addelement**方法,也是一个同步方法,先将修改次数加一,之后调用**ensurecapacityhelper**确认数组有足够的空间能够容纳新的元素。最后将元素新增到数组,即vector的末尾。
#### 3.出栈pop
public synchronized e pop() {
e obj;
int len = size();
obj = peek();
removeelementat(len - 1);
return obj;
出栈同样是一个同步方法,先定义一个泛型对象obj,获取到数组长度len,然后调用**peek()**方法,获取栈顶的元素赋值给obj,然后删除栈顶元素。
public synchronized e peek() {
if (len == 0)
throw new emptystackexception();
return elementat(len - 1);
很显然,peek()方法直接调用了vector的elementat方法,该方法不删除栈顶的元素。
#### 4.判断栈是否为空
/**
* 通过数组长度判断栈是否为空。
*
* @return <code>true</code> if and only if this stack contains
* no items; <code>false</code> otherwise.
*/
public boolean empty() {
return size() == 0;
#### 5.查询元素到栈顶的距离
* returns the 1-based position where an object is on this stack.
* if the object <tt>o</tt> occurs as an item in this stack, this
* method returns the distance from the top of the stack of the
* occurrence nearest the top of the stack; the topmost item on the
* stack is considered to be at distance <tt>1</tt>. the <tt>equals</tt>
* method is used to compare <tt>o</tt> to the
* items in this stack.
* @param o the desired object.
* @return the 1-based position from the top of the stack where
* the object is located; the return value <code>-1</code>
* indicates that the object is not on the stack.
public synchronized int search(object o) {
int i = lastindexof(o);
if (i >= 0) {
return size() - i;
}
return -1;
一个同步方法,找到指定元素o到栈顶的距离,可以看到用到了lastindexof方法,如果找不到元素,则返回-1。
## 三、总计
通过源码我们可以看到vector底层是一个数组,说明stack的实现是通过数组来实现的,然后通过对数组的操作来模仿栈的各种功能。而且在源码中vector的很多方法都是synchronized 的,也就是说是线程安全,所以说在多线程中是可以安全使用的,不过这样效率上肯定是会降低的。