java 栈的分析

来源:互联网 发布:淘宝客服那那里应聘 编辑:程序博客网 时间:2024/06/08 11:57

1. 系统提供的Stack 的方法如下:

java 栈图片

2. 集成关系如下:

这里写图片描述

由上图可见,Stack 的底层是数组,因为继承了Vector ,AbstractList.

3. Stack的常用方法


进栈:

//Stack 中方法:public E push(E item) {     addElement(item);     return item; }// vector 中方法public synchronized void addElement(E obj) {      modCount++;      ensureCapacityHelper(elementCount + 1);      elementData[elementCount++] = obj;  }

出栈:

// Stack 中方法public synchronized E pop() {     E       obj;     int     len = size();     obj = peek();     removeElementAt(len - 1);     return obj; }// vector 中方法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 */  }

peek 方法: 取出数值,但不弹出数据

public synchronized E peek() {     int     len = size();     if (len == 0)         throw new EmptyStackException();     return elementAt(len - 1); }
原创粉丝点击