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 }
  • 相关阅读:
    线程状态转换
    CyclicBarrier和CountDownLatch区别
    MySQL事务原理
    DownLoadManager[20530:228829] DiskImageCache: Could not resolve the absolute path of the old directory.
    App各种Icon及Launch image的尺寸和用途
    关于iPhone开发的一些建议
    iPhone6/6Plus下app状态栏内容放大问题处理
    PDF转jpg
    ios开发学习笔记
    nil和Nil和NULL的判断
  • 原文地址:https://www.cnblogs.com/shizhh/p/5774287.html
Copyright © 2011-2022 走看看