一.繼承
? ? 繼承自Vector類
二.核心方法分析
2.1push方法
? public E push(E item) {
????addElement(item);
? ?return item;
}
調(diào)用Vector類中addElement方法粘咖,新增元素,addElement是添加了synchronized鎖的靴寂,是線程安全的
2.2peek()方法
public synchronized E peek() {
????int? ? len = size();
? ? if (len ==0)
????????throw new EmptyStackException();
? ? return elementAt(len -1);
}
peek()方法也是添加了synchronized鎖的赢织,主要是這里要用到size()方法需要進行加鎖
peek()返回最后的元素,但是元素并不會彈出
2.3pop方法
public synchronized E pop() {
????E? ? ? obj;
? ? int? ? len = size();
? ? obj = peek();
? ? removeElementAt(len -1);
? ? return obj;
}
這里的pop()方法調(diào)用了peek()方法獲取元素,并且將這個元素從數(shù)組中移除
2.4removeElementAt方法
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 */
}
這個方法屬于Vector類情屹,首先會對index進行下校驗,后面會將index后面的元素向前移動一個位置
元素總數(shù)減一杂腰,最后一個元素設(shè)置為null垃你,方便進行垃圾回收