栈在jdk中的实现

类 public class Stack extends Vector 是泛型 泛型的存在是增加代码的通用性
查看api可以看到主要有一下几个方法

Modifier and Type Method and Description
boolean empty()
Tests if this stack is empty.
E peek()
Looks at the object at the top of this stack without removing it from the stack.
E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)
Pushes an item onto the top of this stack.
int search(Object o)
Returns the 1-based position where an object is on this stack.

首先看push 数据是怎么存入栈中的;
public E push(E item) {
addElement(item);

    return item;
}

public synchronized void addElement(E obj) {
modCount++;//此结构列表的修改次数
ensureCapacityHelper(elementCount + 1);//确保容量 elementCount 现有元素个数
elementData[elementCount++] = obj;//赋值
}

在看下 ensureCapacityHelper方法;
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)//如果当前(elementCount + 1)大于数组长度,就需要扩容
grow(minCapacity);
}

栈的底层实现是数组,只是在方法级别实现了栈的先入后出的逻辑;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//计算目标容量,如果指定了每次扩展的量,直接增加,如果没有就直接翻倍
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);//数组复制方法
}

再来看下出栈pop
public synchronized E pop() {
E obj;
int len = size();//元素占用的容量

    obj = peek();栈顶元素返回
    removeElementAt(len - 1);//移除最后元素

    return obj;
}

peek方法如下
public synchronized E peek() {
int len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);//返回最后一个元素
}


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 */ 最后一个元素为null
}

peek 不改变数组元素
public synchronized E peek() {
int len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晴天M雨天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值