Stack源码学习
一、介绍
1、Stack 称为栈(LIFO)后进先出,Stack是继承于Vector(矢量队列)的,Vector底层是数组实现
二、示意图
三、特点
栈(stack),是一种线性存储结构,它有以下几个特点:
1、栈中数据是按照"后进先出(LIFO, Last In First Out)"方式进出栈的
2、向栈中添加/删除数据时,只能从栈顶进行操作
四、源码分析
1、默认构造函数
public Stack() {
}
2、push 添加元素并返回元素
public E push(E item) {
addElement(item);//调用父类的方法进行添加元素
return item;
}
//父类Vector
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);//判断数组容量
elementData[elementCount++] = obj;//将元素添加到数组最后
}
3、pop 返回栈顶元素并删除元素、线程安全
public synchronized E pop() {
E obj;
int len = size();//调用父类size方法获取数组元素个数
obj = peek();
removeElementAt(len - 1);//调用父类removeElementAt方法删除栈顶元素
return obj;
}
//父类Vector的size方法,返回数组的元素个数
public synchronized int size() {
return elementCount;
}
//父类Vector的removeElementAt方法,根据数组下标删除元素
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
4、peek 返回栈顶元素、线程安全
public synchronized E peek() {
int len = size();//调用父类size方法获取数组元素个数
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);//调用父类elementAt方法获取栈顶元素
}
//父类Vector的elementAt方法,根据数组下标获取元素
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
5、empty 判断栈中元素是否为空、返回布尔型
public boolean empty() {
return size() == 0;//调用父类size方法获取数组元素个数
}
6、serach 根据元素查询元素所在栈的位置
public synchronized int search(Object o) {
int i = lastIndexOf(o);//调用父类方法根据元素查找到数组下标
if (i >= 0) {
return size() - i;//根据栈的特性获取元素在栈的位置
}
return -1;
}
//父类方法根据元素查找到数组下标
public synchronized int lastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}