java中Stack的源码解析

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

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

     public   class Stack<E> extends Vector<E> {

                

          /**
           * 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 <tt>o</tt> 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 <tt>1</tt>. The <tt>equals</tt>
       * method is used to compare <tt>o</tt> 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中栈的实现,估不在做解释。

 

 

猜你喜欢

转载自www.cnblogs.com/caibixiang123/p/9257441.html
今日推荐