类 public class Stack extends Vector 是泛型 泛型的存在是增加代码的通用性
查看api可以看到主要有一下几个方法
Modifier and Type Method and Description
boolean empty()
Tests if this stack is empty.
E peek()
Looks at the object at the top of this stack without removing it from the stack.
E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)
Pushes an item onto the top of this stack.
int search(Object o)
Returns the 1-based position where an object is on this stack.
首先看push 数据是怎么存入栈中的;
public E push(E item) {
addElement(item);
return item;
}
public synchronized void addElement(E obj) {
modCount++;//此结构列表的修改次数
ensureCapacityHelper(elementCount + 1);//确保容量 elementCount 现有元素个数
elementData[elementCount++] = obj;//赋值
}
在看下 ensureCapacityHelper方法;
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果当前(elementCount + 1)大于数组长度,就需要扩容
grow(minCapacity);
}
栈的底层实现是数组,只是在方法级别实现了栈的先入后出的逻辑;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//计算目标容量,如果指定了每次扩展的量,直接增加,如果没有就直接翻倍
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);//数组复制方法
}
再来看下出栈pop
public synchronized E pop() {
E obj;
int len = size();//元素占用的容量
obj = peek();栈顶元素返回
removeElementAt(len - 1);//移除最后元素
return obj;
}
peek方法如下
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);//返回最后一个元素
}
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 */ 最后一个元素为null
}
peek 不改变数组元素
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}