一 属性
protected Object[] elementData;protected int elementCount;//每次扩容的大小protected int capacityIncrement;private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
二 重要方法
- 使用Synchronized关键字保证线程安全
ensureCapacity(int minCapacity)
扩容(每次扩容一个伐值 capacityIncrement)
三 添加元素
//使用synchronized关键字保证线程安全public synchronized boolean add(E e) {modCount++;ensureCapacityHelper(elementCount + 1);elementData[elementCount++] = e;return true;}
四 删除元素
public synchronized E remove(int index) {modCount++;if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);E 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 workreturn oldValue;}
五 获取元素
//注意这里获取元素也被加锁了 防止脏读现象public synchronized E get(int index) {if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);return elementData(index);}
六 其他
Stack 继承Vector
- push 入栈
- pop 出栈,线程安全的,实际先调用peek()获取元素,再调用removeElementAt 删除元素
- peek 返回栈顶元素
