1、push()方法,压入数据到栈底
public E push(E item) {
addElement(item);
return item;
}
点击addElement会进入到Vector当中去,Vector是个有序和
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
ensureCapacityHelper是判断是否要对数组扩容,逻辑和ArrayList几乎一样。所不同的是ArrayList每次扩容是1.5倍,Vector每次扩容默认是2倍。
2、pop方法,从栈顶弹出数据
1) pop()方法
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
点击peek()进入步骤2)
点击removeElementAt()进入步骤3)
2) peek() 方法
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1); //获取最后一个元素返回
}
3)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 */
}
这行代码表示如果要删除的不是最上面的元素,则需要复制到另一个栈。
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
删除最后一个元素,其实就是将其设置为null即可。
elementData[elementCount] = null;