Stack和Vector源码分析

stack源码分析

1.Stack是什么

Stack是栈。它的特性是:先进后出(FILO, First In Last Out)。

java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的,而非链表。

2.Stack的结构图

3.Stack继承关系

java.lang.Object
↳     java.util.AbstractCollection<E>
   ↳     java.util.AbstractList<E>
       ↳     java.util.Vector<E>
           ↳     java.util.Stack<E>

public class Stack<E> extends Vector<E> {}

4.Stack的主要方法

             boolean       empty()//判断这个栈是不是空栈
synchronized E             peek()//查看栈顶元素,但是不将栈顶元素移除
synchronized E             pop()//出栈:移除栈顶元素,返回移除的栈顶元素
             E             push(E object)//入栈:增加元素到栈顶,并返回这个元素
synchronized int           search(Object o)//从栈顶开始寻找第一次出现的指定元素,并返回栈顶和指定元素的距离

5.Stack源码

我们可以看到,Stack源码很少,它的大部分功能都是通过调用父类的Vector的方法来实现的。所有我们要想学好Stack,最好先看Vector的源码。

package list;
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack<E> extends Vector<E> {
    //构造函数
    public Stack() {
    }
    /**
     * 入栈:增加元素到栈顶,并返回这个元素
     */
    public E push(E item) {
        addElement(item);//调用vector的addElement方法添加
        return item;
    }
    /**
     * 出栈:移除栈顶元素,返回移除的栈顶元素
     */
    public synchronized E pop() {
        E obj;
        int len = size();//vector的方法,元素多少

        obj = peek();//查看栈顶元素
        removeElementAt(len - 1);//将栈顶元素移除
        return obj;
    }
    /**
     * 查看栈顶元素,但是不将栈顶元素移除
     */
    public synchronized E peek() {
        int len = size();

        if (len == 0)
            throw new EmptyStackException();
        return elementAt(len - 1);
    }
    /**
     * 判断这个栈是不是空栈
     */
    public boolean empty() {
        return size() == 0;
    }
    /**
     * 从栈顶开始寻找第一次出现的指定元素,并返回栈顶和指定元素的距离
     * -- 如果栈中没有这个元素,返回-1
     * -- 最小的距离是1(如果栈顶元素就是要找的元素,距离为1)
     */
    public synchronized int search(Object o) {
        int i = lastIndexOf(o);//调用父类方法,从栈顶开始查找第一次出现指定元素的位置

        if (i >= 0) {//如果有指定元素
            return size() - i;//返回栈顶和指定元素的距离
        }
        return -1;
    }
    /**
     *序列化
     */
    private static final long serialVersionUID = 1224463164541339165L;
}

Vector源码分析

1.vector介绍

Vector是矢量队列,它继承了AbstractList,实现了List、 RandomAccess, Cloneable, java.io.Serializable接口。

  • Vector继承了AbstractList,实现了List,它是一个队列,因此实现了相应的添加、删除、修改、遍历等功能。
  • Vector实现了RandomAccess接口,因此可以随机访问。
  • Vector实现了Cloneable,重载了clone()方法,因此可以进行克隆。
  • Vector实现了Serializable接口,因此可以进行序列化。
  • Vector的操作是线程安全的。

2.vector的关系图

3.vector和ArrayList的关系

Vector的数据结构和ArrayList差不多,包含了3个成员变量:elementData,elementCount,capacityIncrement。

(1)elementData是Object[]的数组,初始大小为10,会不断的增长。

(2)elementCount是元素的个数。

(3)capacityIncrement是动态数组增长的系数。

4.Vector的大致图像

5.Vector的源码

vector和ArrayList都是数组类型,分析Vector源码你就会发现和ArrayList的源码非常相似,如果你分析过ArrayList的源码,Vector的源码看起来一点问题都没有。这里用的是1.8版本

package list;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;

public class Vector<E>
        extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    //当前数组
    protected Object[] elementData;

    //当前数组元素个数
    protected int elementCount;

   // capacityIncrement,扩增容量:代表当列表元素满了之后增加的容量。
    //如果不设置capacityIncrement,那么Vector容量扩展时默认将扩展两倍
    protected int capacityIncrement;

    //序列化uid
    private static final long serialVersionUID = -2767605614048989439L;

    /**
     * 创建一个带有指定容量和扩增容量的Vector
     * @param   initialCapacity     初始化容量
     * @param   capacityIncrement   列表元素满了之后增加的容量
     * @throws IllegalArgumentException 如果指定容量为负
     */
    public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                    initialCapacity);
        this.elementData = new Object[initialCapacity];//创建一个指定容量的数组
        this.capacityIncrement = capacityIncrement;
    }

    /**
     * 创建一个带有指定容量和扩增容量为空的Vector
     */
    public Vector(int initialCapacity) {
        this(initialCapacity, 0);
    }

    /**
     * 创建一个带有指定容量和扩增容量为空的Vector
     */
    public Vector() {
        this(10);
    }

    /**
     * 创建一个包含指定集合中元素的Vector,
     *  - 顺序按照集合的iterator
     *  - <? extends E>  协变: 当你传入的集合是 E 的子类时,那么就可以协变。
     */
    public Vector(Collection<? extends E> 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);
    }

    /**
     * 将Vector中的元素拷贝到指定数组中
     */
    public synchronized void copyInto(Object[] anArray) {
        System.arraycopy(elementData, 0, anArray, 0, elementCount);
    }

    /**
     * 修剪空间
     */
    public synchronized void trimToSize() {
        modCount++;
        int oldCapacity = elementData.length;
        if (elementCount < oldCapacity) {
            elementData = Arrays.copyOf(elementData, elementCount);
        }
    }

    /**
     * 确保最小容量至少是minCapacity,如果不够,增长Vector的容量
     */
    public synchronized void ensureCapacity(int minCapacity) {
        if (minCapacity > 0) {
            modCount++;
            ensureCapacityHelper(minCapacity);
        }
    }

    /**
     * 这里注释解释,这个方法是异步(也就是能被多个线程同时访问)的,
     * 原因是为了让同步方法都能调用到这个检测容量的方法,
     */
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            //容量不够,就扩增,核心方法
            grow(minCapacity);
    }

    /**
     * 数组分配的最大容量,一些VMs尝试分配更大的数组,可能会导致内存泄漏
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 容量核心方法,增加容量
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        //原来的数组容量
        int oldCapacity = elementData.length;
        //扩容后的容量,如果capacityIncrement为指定扩容后的容量为原来容量的两倍
        //如果指定了增长容量,扩容后的容量为原来容量+增长容量
        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);//新数组大小
    }

    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

    /**
     * 设置vector的容量大小,如果新容量大于当前的容量,则增加items到vector的末尾
     *   如果新容量小于当前容量,将vector从新容量到末尾处丢弃
     */
    public synchronized void setSize(int newSize) {
        modCount++;
        if (newSize > elementCount) {
            ensureCapacityHelper(newSize);
        } else {
            for (int i = newSize ; i < elementCount ; i++) {
                elementData[i] = null;
            }
        }
        elementCount = newSize;
    }

    /**
     * 获取vector的容量
     */
    public synchronized int capacity() {
        return elementData.length;
    }

    /**
     * 返回 vector 元素个数
     */
    public synchronized int size() {
        return elementCount;
    }

    /**
     * 判断vector元素是否为空
     */
    public synchronized boolean isEmpty() {
        return elementCount == 0;
    }

    /**
     * 返回一个包含vector所有元素的枚举
     * while (elements.hasMoreElements()) {
     *       String s = elements.nextElement();
     *       }
     */
    public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

    /**
     * 返回这个vector是否包含指定元素
     */
    public boolean contains(Object o) {
        return indexOf(o, 0) >= 0;
    }

    /**
     * 返回这个vector中第一次出现指定元素的下标,如果不包括这个元素返回-1
     * 从0开始查找
     */
    public int indexOf(Object o) {
        return indexOf(o, 0);
    }

    /**
     *从指定的位置向后开始查找vector中第一次出现这个元素的下标
     * 如果没有返回-1
     */
    public synchronized int indexOf(Object o, int index) {
        if (o == null) {
            for (int i = index ; i < elementCount ; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index ; i < elementCount ; i++)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 返回在vector中最后一次出现指定元素的角标
     * 如果vector不包含这个元素则返回-1
     */
    public synchronized int lastIndexOf(Object o) {
        return lastIndexOf(o, elementCount-1);
    }

    /**
     * 返回在vector中最后一次出现指定元素的角标
     * - 就是从指定位置向前寻找第一次出现的指定元素的角标
     * - 如果找不到返回-1
     */
    public synchronized int lastIndexOf(Object o, int index) {
        if (index >= elementCount)
            throw new IndexOutOfBoundsException(index + " >= "+ elementCount);

        if (o == null) {
            for (int i = index; i >= 0; i--)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = index; i >= 0; i--)
                if (o.equals(elementData[i]))
                    return i;
        }
        return -1;
    }

    /**
     * 返回指定下标的元素
     * -- 这个只判断了index>elcmentCount
     */
    public synchronized E elementAt(int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
        }

        return elementData(index);
    }

    /**
     *返回vector中的第一个元素
     * -- 如果没有元素会报错NoSuchElementException
     */
    public synchronized E firstElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(0);
    }

    /**
     *返回vector中的最后一个元素,
     * -- 如果没有会报错NoSuchElementException
     */
    public synchronized E lastElement() {
        if (elementCount == 0) {
            throw new NoSuchElementException();
        }
        return elementData(elementCount - 1);
    }

    /**
     * 在指定位置设置指定元素,原来位置的元素会被丢弃
     */
    public synchronized void setElementAt(E obj, int index) {
        if (index >= elementCount) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    elementCount);
        }
        elementData[index] = obj;
    }

    /**
     * 删除指定位置的元素
     * -- 指定位置后面如果还有元素,将后面的元素都向下移动1
     * -- 元素长度-1
     */
    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;//将元素顶部置空,方便回收器回收
    }

    /**
     * 在指定位置插入元素
     * -- 将指定位置后面的元素(包括指定位置)向上移动一位
     */
    public synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > elementCount) {
            throw new ArrayIndexOutOfBoundsException(index
                    + " > " + elementCount);
        }
        ensureCapacityHelper(elementCount + 1);//确保容量够用
        //将指定位置及其后面的元素向上移动一位
        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
        //在指定位置插入元素
        elementData[index] = obj;
        //元素长度+1
        elementCount++;
    }

    /**
     * 在vector的元素末尾添加一个元素
     */
    public synchronized void addElement(E obj) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);//确保容量够用
        elementData[elementCount++] = obj;
    }

    /**
     * 移除在vector中第一次出现的指定元素
     * -- 如果vector中真的包含这个元素,这个元素后面的都要向下移动一位
     */
    public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);//查找元素在vector中的位置,如果没有返回-1
        if (i >= 0) {
            //如果有这个元素,删除
            removeElementAt(i);
            return true;
        }
        return false;
    }

    /**
     * 移除vector中的所有元素,让它的元素大小为0
     */
    public synchronized void removeAllElements() {
        modCount++;
        // 让回收器回收
        for (int i = 0; i < elementCount; i++)
            elementData[i] = null;
        elementCount = 0;
    }

    /**
     * 由于实现了Cloneable,这个是深度克隆
     */
    public synchronized Object clone() {
        try {
            @SuppressWarnings("unchecked")
            Vector<E> v = (Vector<E>) super.clone();
            v.elementData = Arrays.copyOf(elementData, elementCount);
            v.modCount = 0;
            return v;
        } catch (CloneNotSupportedException e) {
            // this shouldn't happen, since we are Cloneable
            throw new InternalError(e);
        }
    }

    /**
     * 返回一个数组,包含vector中的所有元素
     */
    public synchronized Object[] toArray() {
        return Arrays.copyOf(elementData, elementCount);
    }

    /**
     * 返回指定类型的数组
     * - 这里T[] 可以是vector中指定的类型的父类
     */
    @SuppressWarnings("unchecked")
    public synchronized <T> T[] toArray(T[] a) {
        if (a.length < elementCount)
            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());

        System.arraycopy(elementData, 0, a, 0, elementCount);

        if (a.length > elementCount)
            a[elementCount] = null;

        return a;
    }

    // Positional Access Operations
    //返回指定位置的元素
    //-- 没有检查,这个方法被内部方法调用
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 获取指定位置的元素
     */
    public synchronized E get(int index) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    /**
     * 在vector的指定位置代替指定的元素
     * -- 返回指定位置原来的元素
     */
    public synchronized E set(int index, E element) {
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

    /**
     * 增加指定的元素到vector
     */
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(elementCount + 1);//确保vector的容量够用
        elementData[elementCount++] = e;//填充元素
        return true;
    }

    /**
     * 移除vector中第一次出现的指定元素
     */
    public boolean remove(Object o) {
        return removeElement(o);
    }

    /**
     * 在指定位置插入指定元素
     * --向上移动当前元素和后续元素
     */
    public void add(int index, E element) {
        insertElementAt(element, index);
    }

    /**
     *移除指定位置的元素
     * -- 返回指定位的原来元素
     * -- 向下移动指定位置后续的元素
     */
    public synchronized E remove(int index) {
        modCount++;
        if (index >= elementCount)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);//获取指定位的元素

        int numMoved = elementCount - index - 1;//获取指定位置后面的元素个数
        if (numMoved > 0)
            //向下移动指定位置的后续元素
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        elementData[--elementCount] = null; // Let gc do its work

        return oldValue;
    }

    /**
     * 清除vector中的所有元素
     */
    public void clear() {
        removeAllElements();
    }

    // Bulk Operations

    /**这个方法是调用父类AbstractCollection的方法实现的
     * vector是否包含指定集合中的所有元素
     * -- 如果指定集合中有一个元素不包含则返回false
     */
    public synchronized boolean containsAll(Collection<?> c) {
        return super.containsAll(c);
    }

    /**
     * 添加指定集合中的所有元素到vector的末尾,
     * --按照指定集合iterator返回的顺序
     */
    public synchronized boolean addAll(Collection<? extends E> c) {
        modCount++;
        Object[] a = c.toArray();//将集合转化成数组
        int numNew = a.length;//集合的长度
        ensureCapacityHelper(elementCount + numNew);//确保容量
        System.arraycopy(a, 0, elementData, elementCount, numNew);//拷贝
        elementCount += numNew;
        return numNew != 0;
    }

    /**
     * 这个方法是调用父类AbstractCollection的方法实现的
     * 删除vector中指定集合的所有元素
     * -- 如 vector[2,5,7,10,3,] c[5,3,15] 指行这个方法后,vector中[2,7,10,3]
     */
    public synchronized boolean removeAll(Collection<?> c) {
        return super.removeAll(c);
    }

    /**
     * 这个是调用父类AbstractCollection方法实现的
     * 保留vector中指定集合的所有元素
     * -- 如 vector[2,5,7,10,3,] c[5,3,15] 指行这个方法后,vector中[5,3]
     */
    public synchronized boolean retainAll(Collection<?> c) {
        return super.retainAll(c);
    }

    /**
     * 在vector的指定位置添加指定集合中的所有元素
     * -- 向右移动指定位置及其后继的元素
     */
    public synchronized boolean addAll(int index, Collection<? extends E> c) {
        modCount++;
        if (index < 0 || index > elementCount)
            throw new ArrayIndexOutOfBoundsException(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        ensureCapacityHelper(elementCount + numNew);

        int numMoved = elementCount - index;//指定位置及其后继元素的个数
        if (numMoved > 0)
            //向后移动集合元素大小个距离
            System.arraycopy(elementData, index, elementData, index + numNew,
                    numMoved);
        //将集合元素添加到vector中
        System.arraycopy(a, 0, elementData, index, numNew);
        elementCount += numNew;
        return numNew != 0;
    }

    /**
     * 这个方法是调用父类AbstractList方法实现的
     * 比较vector和指定的对象
     * 如果 这个对象是List对象而且集合中元素和vector中的元素一致则返回true,否则返回false
     */
    public synchronized boolean equals(Object o) {
        return super.equals(o);
    }

    /**
     * 返回vector的hashCode
     */
    public synchronized int hashCode() {
        return super.hashCode();
    }

    /**
     * 调用了父类的AbstractCollection中的方法
     * 返回了这个vector的表示string,包括每一个元素的表示
     */
    public synchronized String toString() {
        return super.toString();
    }

    /**
     *
     *返回list中的[fromIndex,toIndex]的子视图
     * -- 如果fromIndex==toIndex则返回的是一个空视图
     * --  这个子视图是这个List的反射
     */
    public synchronized List<E> subList(int fromIndex, int toIndex) {
        return Collections.synchronizedList(super.subList(fromIndex, toIndex));
    }

    /**
     * 移除list中[fromIndex,toIndex)范围的元素
     * toIndex及其后继元素向前移动toIndex-fromIndex位
     */
    protected synchronized void removeRange(int fromIndex, int toIndex) {
        modCount++;
        int numMoved = elementCount - toIndex;//获取要移动元素的个数
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                numMoved);

        // 回收
        int newElementCount = elementCount - (toIndex-fromIndex);
        while (elementCount != newElementCount)
            elementData[--elementCount] = null;
    }

    /**
     * 序列化
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }
    //--------下面的视图iterator,可以参考ArrayList的
    /**
     * 迭代器
     */
    public synchronized ListIterator<E> listIterator(int index) {
        if (index < 0 || index > elementCount)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
    }

    /**
     * Returns a list iterator over the elements in this list (in proper
     * sequence)
     */
    public synchronized ListIterator<E> listIterator() {
        return new ListItr(0);
    }

    /**
     * Returns an iterator over the elements in this list in proper sequence.
     *
     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
     *
     * @return an iterator over the elements in this list in proper sequence
     */
    public synchronized Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            // Racy but within spec, since modifications are checked
            // within or after synchronization in next/previous
            return cursor != elementCount;
        }

        public E next() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor;
                if (i >= elementCount)
                    throw new NoSuchElementException();
                cursor = i + 1;
                return elementData(lastRet = i);
            }
        }

        public void remove() {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.remove(lastRet);
                expectedModCount = modCount;
            }
            cursor = lastRet;
            lastRet = -1;
        }

        @Override
        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            synchronized (Vector.this) {
                final int size = elementCount;
                int i = cursor;
                if (i >= size) {
                    return;
                }
                @SuppressWarnings("unchecked")
                final E[] elementData = (E[]) Vector.this.elementData;
                if (i >= elementData.length) {
                    throw new ConcurrentModificationException();
                }
                while (i != size && modCount == expectedModCount) {
                    action.accept(elementData[i++]);
                }
                // update once at end of iteration to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

    /**
     * An optimized version of AbstractList.ListItr
     */
    final class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {
            return cursor != 0;
        }

        public int nextIndex() {
            return cursor;
        }

        public int previousIndex() {
            return cursor - 1;
        }

        public E previous() {
            synchronized (Vector.this) {
                checkForComodification();
                int i = cursor - 1;
                if (i < 0)
                    throw new NoSuchElementException();
                cursor = i;
                return elementData(lastRet = i);
            }
        }

        public void set(E e) {
            if (lastRet == -1)
                throw new IllegalStateException();
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.set(lastRet, e);
            }
        }

        public void add(E e) {
            int i = cursor;
            synchronized (Vector.this) {
                checkForComodification();
                Vector.this.add(i, e);
                expectedModCount = modCount;
            }
            cursor = i + 1;
            lastRet = -1;
        }
    }

    @Override
    public synchronized void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int elementCount = this.elementCount;
        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final int size = elementCount;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            elementCount = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

        return anyToRemove;
    }

    @Override
    @SuppressWarnings("unchecked")
    public synchronized void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = elementCount;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    @SuppressWarnings("unchecked")
    @Override
    public synchronized void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, elementCount, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

    /**
     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
     * list.
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
     * Overriding implementations should document the reporting of additional
     * characteristic values.
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new VectorSpliterator<>(this, null, 0, -1, 0);
    }

    /** Similar to ArrayList Spliterator */
    static final class VectorSpliterator<E> implements Spliterator<E> {
        private final Vector<E> list;
        private Object[] array;
        private int index; // current index, modified on advance/split
        private int fence; // -1 until used; then one past last index
        private int expectedModCount; // initialized when fence set

        /** Create new spliterator covering the given  range */
        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
                          int expectedModCount) {
            this.list = list;
            this.array = array;
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // initialize on first use
            int hi;
            if ((hi = fence) < 0) {
                synchronized(list) {
                    array = list.elementData;
                    expectedModCount = list.modCount;
                    hi = fence = list.elementCount;
                }
            }
            return hi;
        }

        public Spliterator<E> trySplit() {
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null :
                    new VectorSpliterator<E>(list, array, lo, index = mid,
                            expectedModCount);
        }

        @SuppressWarnings("unchecked")
        public boolean tryAdvance(Consumer<? super E> action) {
            int i;
            if (action == null)
                throw new NullPointerException();
            if (getFence() > (i = index)) {
                index = i + 1;
                action.accept((E)array[i]);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> action) {
            int i, hi; // hoist accesses and checks from loop
            Vector<E> lst; Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((lst = list) != null) {
                if ((hi = fence) < 0) {
                    synchronized(lst) {
                        expectedModCount = lst.modCount;
                        a = array = lst.elementData;
                        hi = fence = lst.elementCount;
                    }
                }
                else
                    a = array;
                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
                    while (i < hi)
                        action.accept((E) a[i++]);
                    if (lst.modCount == expectedModCount)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        public long estimateSize() {
            return (long) (getFence() - index);
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}

Stack和Vector源码分析的更多相关文章

  1. ArrayList、LinkedList和Vector源码分析

    ArrayList.LinkedList和Vector源码分析 ArrayList ArrayList是一个底层使用数组来存储对象,但不是线程安全的集合类 ArrayList的类结构关系 public ...

  2. Vector源码分析和实例应用

    1.Vector介绍 Vector 是矢量队列,它是JDK1.0版本添加的类.继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口. Vector ...

  3. Java集合之Vector源码分析

    概述 Vector与ArrayLIst类似, 内部同样维护一个数组, Vector是线程安全的. 方法与ArrayList大体一致, 只是加上 synchronized 关键字, 保证线程安全, 下面 ...

  4. Vector源码分析

    Vector与ArrayList底层实现基本类似,底层都是用数组实现的,最大的不同是Vector是线程安全的.ArrayList源码分析请参考ArrayList源码分析 一.源码分析 基于jdk1.7 ...

  5. [Java]Vector源码分析

    第1部分 Vector介绍 Vector简介 Vector也是基于数组实现的,是一个动态数组,其容量能自动增长.继承于AbstractList,实现了List, RandomAccess, Clone ...

  6. ArrayList和LinkedList和Vector源码分析

    ArrayList源码: private static final int DEFAULT_CAPACITY = 10;//默认长度 /** * Shared empty array instance ...

  7. Stack&Vector源码分析 jdk1.6

    参照:http://www.cnblogs.com/tstd/p/5104099.html Stack(Fitst In Last Out) 1.定义 public class Stack<E& ...

  8. Vector和Stack源码分析/List集合的总结

    序言 这篇文章算是在这list接口下的集合的最后一篇了,前面ArrayList.LinkedList都已经讲解完了,剩下就Vector和Vector的子类Stack啦.继续努力.一步一个脚印, --W ...

  9. Java集合源码分析(三)Vevtor和Stack

    前言 前面写了一篇关于的是LinkedList的除了它的数据结构稍微有一点复杂之外,其他的都很好理解的.这一篇讲的可能大家在开发中很少去用到.但是有的时候也可能是会用到的! 注意在学习这一篇之前,需要 ...

随机推荐

  1. 怎样写一个与Windows10 IE11兼容的标准BHO?

    p.MsoNormal,li.MsoNormal,div.MsoNormal { margin: 0cm; margin-bottom: .0001pt; text-align: justify; f ...

  2. C语言中标识符的作用域、命名空间、链接属性、生命周期、存储类型

    Technorati 标签: C,标识符,作用域,命名空间,链接属性,生命周期,存储类型,scope,name space,linkage,storage durations,lifetime 无论学 ...

  3. Socket编程实践(1) --TCP/IP简述

    ISO的OSI OSI(open system interconnection)开放系统互联模型是由ISO国际标准化组织定义的网络分层模型,共七层, 从下往上为: OSI七层参考模型 物理层(Phys ...

  4. (NO.00003)iOS游戏简单的机器人投射游戏成形记(十五)

    在Xcode中打开Robot.h文件添加如下2个方法: -(void)moveArm:(MoveDirection)direction; -(void)armShoot; 在Robot.m中实现这2个 ...

  5. (NO.00003)iOS游戏简单的机器人投射游戏成形记(七)

    因为到目前为止我都是在iOS模拟器中测试,但即便如此,也觉得按住手臂旋转时,手臂转动起来比较费劲,很难停止在玩家期望的位置上.因为手臂完全通过物理引擎的计算来移动,它有自身的惯性影响,所以很难控制. ...

  6. (三十七)从私人通讯录引出的细节I -Notification -Segue -HUD -延时

    细节1:账号和密码都有值的时候才可以点击登录按钮,因此应该监听文本框的文本改变. 因为文本框的文本改变代理不能处理,因此应该使用通知Notification. 文本框文本改变会发出通知:通知的前两个参 ...

  7. (十二)UITableView的基本使用

    UITableView之所以支持滚动,是因为继承自UIScrollView.默认是垂直滚动,性能极佳. UITableView的两种样式: 1.UITableViewStylePlain       ...

  8. 《java入门第一季》之类面试题

    面试题一: String,StringBuffer,StringBuilder的区别?  * A:String是内容不可变的,而StringBuffer,StringBuilder都是内容可变的.   ...

  9. Cocos2d中update与fixedUpdate的区别(二)

    关于update:方法的目的 update:方法的目的在于给你一个更新你的游戏(你游戏中的所有对象,标签等待)的机会,在它们被渲染到屏幕之前. 换句话说,如果你想要一些游戏对象显示在屏幕的特定位置,你 ...

  10. 2015年北京的第一场雪-关于android学习的思考(84)

    今天是2015年11月6日,今天北京下了大雪,我听着民谣,发现丢火车的摇滚也还不错,我身体的一部分毛发也发生了变异,由黑色变成红色,一切来的太突然了......不知不觉学习android开发2年多了, ...