- 继承自
Vector
,是线程安全的
- 在 Java 中,推荐使用 ArrayDeque 来代替 Stack,因为 ArrayDeque 是非线程安全的,性能更好
push
| public E push(E item) { |
| addElement(item); |
| |
| return item; |
| } |
- 调用了
Vector
类的 addElement
方法,该方法上添加了 synchronized
关键字
| public synchronized void addElement(E obj) { |
| modCount++; |
| ensureCapacityHelper(elementCount + 1); |
| elementData[elementCount++] = obj; |
| } |
pop
| public synchronized E pop() { |
| E obj; |
| int len = size(); |
| |
| |
| obj = peek(); |
| removeElementAt(len - 1); |
| |
| return obj; |
| } |
- 调用 Vector 类的 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; |
| } |
| public synchronized E peek() { |
| int len = size(); |
| |
| if (len == 0) |
| throw new EmptyStackException(); |
| return elementAt(len - 1); |
| } |
本文作者:n1ce2cv
本文链接:https://www.cnblogs.com/sprinining/p/18300968
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步