JDK的Stack源码分析
一.继承
继承自Vector类
二.核心方法分析
2.1push方法
public E push(E item) {
addElement(item);
return item;
}
调用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()方法调用了peek()方法获取元素,并且将这个元素从数组中移除
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后面的元素向前移动一个位置
元素总数减一,最后一个元素设置为null,方便进行垃圾回收