1. 栈定义
在java中Stack类表示后进先出(LIFO)的对象堆栈。栈是一种非常常见的数据结构,它采用典型的先进后出的操作方式完成的。每一个栈都包含一个栈顶,每次出栈是将栈顶的数据取出,如下:
(https://img-blog.csdn.net/20161104232055063)
Stack通过五个操作对Vector进行扩展,允许将向量视为堆栈。这个五个操作如下:
操作 | 说明 |
---|---|
empty() | 测试堆栈是否为空 |
peek() | 查看堆栈顶部的对象,但不从堆栈中移除它 |
pop() | 移除堆栈顶部的对象,并作为此函数的值返回该对象。 |
push(E item) | 把项压入堆栈顶部。 |
search(Object o) | 返回对象在堆栈中的位置,以 1 为基数。 |
2. Stack类源码分析
Stack继承Vector,他对Vector进行了简单的扩展
2.1 Vector源码分析:
构造方法:
public Vector(int initialCapacity,int capacityIncrement){
super();
if(initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
判空:
public synchronized boolean isEmpty(){
return elementCount = 0;
}
返回某个值的位置:
public synchronized indexOf(Object o,int index){
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
返回某个位置的值:
public synchronized E elementAt(int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return (E)elementData[index];
}
从后遍历返回某个值的位置:
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;
}
插入值:
public synchronized void addElement(E obj) {
modCount++;
// 判断容量是否足够,不够则扩容
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
移除某个位置的值:
public synchronized E remove(int index) {
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
Object oldValue = elementData[index];
int numMoved = elementCount - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
elementData[--elementCount] = null; // Let gc do its work
return (E)oldValue;
}
2.2 Stack(继承Vector)源码分析:
public E push(E item) {
addElement(item);
return item;
}
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
public boolean empty() {
return size() == 0;
}
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
3. Stack深入理解
3.1 由于Stack类继承自Vector,通过Vector源码可知其操作方法synchronized同步,则Stack类线程安全。
3.2 Stack并不要求其中保存数据的唯一性,当Stack中有多个相同的item时,调用search方法,只返回与查找对象equal并且离栈顶最近的item与栈顶间距离