java中stack模块_java中Stack的源码解析

栈是一种基于后进先出的数据结构。实现的栈的方式有数组和链表两种数据结构。下面我们来看看java中的Stack源码解析。

//Stack栈继承了 Vector方法,Vector方法是内部是数组实现的,即java中Stack 也是通过数组实现的。下面我们看看Stack如何通过Vector中的方法实现先进后出,实现压栈和出站的

public   class Stack extends Vector {

/**

* Creates an empty Stack.

*/

public Stack() {     }   //对外的构造器实现

/**

*Pushes an item onto the top of this stack.

*将一个元素压如栈顶

* /

public E push(E item) {

addElement(item);//调用vector 中的addElement(E item)方法 ,大家可以看看Vector中该方法是如何实现的,观看源码可知将这个元素添加到了数组的末尾,要是实现先进后出,也就是要把数组的末尾当做栈顶

//顾猜测可以可知出站必然也要从数组的尾部开始,这样才能实现栈的特点。

return item;

}

/**

* Removes the object at the top of this stack and returns that

* object as the value of this function.

移除一个元素从栈顶,并返回移除的元素

*  /

public synchronized E pop() {

E obj;

int len = size();

obj = peek();//获取栈顶元素

removeElementAt(len - 1);//移除数组末尾的元素,从新增也是添加到数组末尾,可以把数组末尾看做栈顶

return obj;

}

/**

*    Looks at the object at the top of this stack without removing it

*    from the stack.

查看栈顶元素不进行出栈(移除)

*/

public synchronized E peek() {

int len = size();

if (len == 0)

throw new EmptyStackException();

return elementAt(len - 1);

}

/**

* Tests if this stack is empty.

*/

public boolean empty() {

return size() == 0;

}

/**

* Returns the 1-based position where an object is on this stack.

* If the object o occurs as an item in this stack, this

* method returns the distance from the top of the stack of the

* occurrence nearest the top of the stack; the topmost item on the

* stack is considered to be at distance 1. The equals

* method is used to compare o to the

* items in this stack.

*获取距离栈顶最近的元素的位置

*/

public synchronized int search(Object o) {

int i = lastIndexOf(o);//从数组末尾开始遍历,取距离栈顶最近的元素

if (i >= 0) {

return size() - i;

}

return -1;

}

java中Stack栈的实现,是通过Vector集合中的方法来实现相应的压栈(push)和出栈(pop),即通过将数组元素的末尾作为栈顶,压栈和出栈从数组尾部进行,从而实现栈的新进后出的功能。栈中的元素放在

Object[]数组中,感兴趣的同学可以自己通过数组来白板编程实现栈。这里重点是介绍java中栈的实现,估不在做解释。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值