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 }
  • 相关阅读:
    Redis 和 Memcached 的区别
    缓存详解
    HTTP常见状态码
    ORM的概念, ORM到底是什么
    remote: Unauthorized fatal: Authentication failed for...
    TR、FN、FP、FN
    <笔记>ue破解
    <笔记>bmp图片数据格式
    三轴加速度数据处理
    智能手环+三轴加速度传感器总结
  • 原文地址:https://www.cnblogs.com/shizhh/p/5774287.html
Copyright © 2011-2022 走看看