Java中Stack类的实现——上源码

/*
 * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.util;

/**
 * The Stack class represents a last-in-first-out
 * (LIFO) stack of objects. It extends class Vector with five
 * operations that allow a vector to be treated as a stack. The usual
 * push and pop operations are provided, as well as a
 * method to peek at the top item on the stack, a method to test
 * for whether the stack is empty, and a method to search
 * the stack for an item and discover how far it is from the top.
 * 

* When a stack is first created, it contains no items. * *

A more complete and consistent set of LIFO stack operations is * provided by the {@link Deque} interface and its implementations, which * should be used in preference to this class. For example: *

   {@code
 *   Deque stack = new ArrayDeque();}
* * @author Jonathan Payne * @since JDK1.0 */
public class Stack<E> extends Vector<E> { /** * Creates an empty Stack. */ public Stack() { } /** * Pushes an item onto the top of this stack. This has exactly * the same effect as: *
     * addElement(item)
* * @param item the item to be pushed onto this stack. * @return the item argument. * @see java.util.Vector#addElement */
public E push(E item) { addElement(item); return item; } /** * Removes the object at the top of this stack and returns that * object as the value of this function. * * @return The object at the top of this stack (the last item * of the Vector object). * @throws EmptyStackException if this stack is empty. */ //从此可以看出Stack类是线程安全的 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. * * @return the object at the top of this stack (the last item * of the Vector object). * @throws EmptyStackException if this stack is empty. */ public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } /** * Tests if this stack is empty. * * @return true if and only if this stack contains * no items; false otherwise. */ public boolean empty() { return size() == 0; } /** * Returns the 1-based position where an object is on this stack. * If the object o 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 1. The equals * method is used to compare o to the * items in this stack. * * @param o the desired object. * @return the 1-based position from the top of the stack where * the object is located; the return value -1 * indicates that the object is not on the stack. */ public synchronized int search(Object o) { int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; } /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = 1224463164541339165L; }

从此可以看出Stack类是继承于Vertor向量,Vector也是基于数组实现的,下面简要分析一下Vector的源码:

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
   //用来保存Vector向量的数组
    protected Object[] elementData;
    //用来保存当前数组长度
    protected int elementCount;
    /*当向量大小大于其容量时,容量自动增长的量。capacityIncrement<=0时候,向量容量增长一倍*/
    protected int capacityIncrement;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -2767605614048989439L;

    /*下面是构造函数*/

     //使用指定的初始容量和容量增量构造一个空的向量
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    //使用指定的初始容量和等于零的容量增量构造一个空向量
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

  //构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零
    public Vector() {
        this(10);
    }

   //构造一个包含指定 collection 中的元素的向量,这些元素按其 collection 的迭代器返回元素的顺序排列
    public Vector(Collection c) {
        elementData = c.toArray();
        elementCount = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }

   //下面会列举在Stack类中用到的Vector中的函数
   //添加新组件(其实我也不知道为什么要叫组件,暂且就认为是一种元素吧),时候要确保向量容量够大,否则就要增加其容量
    public synchronized void addElement(E obj) {
        modCount++;//这个变量的定义没找到。。。
        ensureCapacityHelper(elementCount + 1);
        elementData[elementCount++] = obj;
    }

    //如果向量大小超过其容量,曾要grow其容量
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /*这里调用了Arrays类的静态方法copyOf(int[] original, int newLength) 复制指定的数组,截取或用 0 填充(如有必要),以使副本具有指定的长度*/
      private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
        }

   //返回当前向量的大小,注意函数加了synchronized
    public synchronized int size() {
        return elementCount;
    }

   //移除向量中指定位置处的元素
    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 */ /*哈哈,很清楚的告诉我们,如果删除数组中对象,将其设置为null,这样垃圾回收器好尽快回收*/
    }
    //返回指定位置处的元素值
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

//数组的访问很简单,只要给出下标即可
 E elementData(int index) {
        return (E) elementData[index];
    }
}

下面简单比较一下ArrayList和Vector,两者均实现了List接口。
Vector和ArrayList在使用上非常相似,都可用来表示一组数量可变的对象应用的集合,并且可以随机地访问其中的元素。
1 Vector的方法都是同步的(Synchronized),是线程安全的(thread-safe),而ArrayList的方法不是,由于线程的同步必然要影响性能,因此,ArrayList的性能比Vector好。
2 当Vector或ArrayList中的元素超过它的初始大小时,Vector会将它的容量翻倍,而ArrayList只增加50%的大小,这样,ArrayList就有利于节约内存空间

下面代码是ArrayList类中容量增长方式的实现:

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//右移一位,表示除以2
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

你可能感兴趣的:(数据结构,Java基础)