zoukankan      html  css  js  c++  java
  • 【JDK1.8】Java 栈实现方式

    看到一道面试题,问Java中栈的实现方式,记录下一些实现细节。

    API中有5个方法,分别是:

    1 boolean empty()
    2 E peek()
    3 E pop()
    4 E push()
    5 int search(Object o)

    Java中stack继承vector,底层实现方式是数组

    push:在数组末尾添加元素,添加之前保证数组容量足够。容量不够的话需要扩容,扩容策略如下:

    int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);

     1 public E push(E item) {
     2         addElement(item);
     3 
     4         return item;
     5 }
     6 
     7 public synchronized void addElement(E obj) {
     8         modCount++;
     9         ensureCapacityHelper(elementCount + 1);
    10         elementData[elementCount++] = obj;
    11 }

    pop:取出数组末尾元素,并删除

     1 public synchronized E pop() {
     2         E       obj;
     3         int     len = size();
     4 
     5         obj = peek();
     6         removeElementAt(len - 1);
     7 
     8         return obj;
     9 }
    10 public synchronized void removeElementAt(int index) {
    11         modCount++;
    12         if (index >= elementCount) {
    13             throw new ArrayIndexOutOfBoundsException(index + " >= " +
    14                                                      elementCount);
    15         }
    16         else if (index < 0) {
    17             throw new ArrayIndexOutOfBoundsException(index);
    18         }
    19         int j = elementCount - index - 1;
    20         if (j > 0) {
    21             System.arraycopy(elementData, index + 1, elementData, index, j);
    22         }
    23         elementCount--;
    24         elementData[elementCount] = null; /* to let gc do its work */
    25 }

    peek:取出数组末尾元素,不删除

    1 public synchronized E peek() {
    2         int     len = size();
    3 
    4         if (len == 0)
    5             throw new EmptyStackException();
    6         return elementAt(len - 1);
    7 }
  • 相关阅读:
    《C++ Primer》读书笔记—第十章 泛型算法
    悬浮在activity上的activity对话框
    android 双向滑动 稍加改进,可做成QQHD效果
    android String.format
    使用ttf字体
    UI界面设计准则
    scrollview gn gridview混合使用问题
    android Activity 之间传递复杂对象
    android程序获取手机imei方法
    android 自定义对话框
  • 原文地址:https://www.cnblogs.com/shizhh/p/5774287.html
Copyright © 2011-2022 走看看