Java集合之Vector、Stack

来源:互联网 发布:usb网络共享电脑驱动xp 编辑:程序博客网 时间:2024/04/28 10:52

  Vector类中大部分方法都在前面详细写过,方法内部的实现就不再重复。

//Vector类可以实现可增长的对象数组,实现了RandomAccess接口,随机访问速度快。线程安全。                JDK1.7           java.utilpublic class Vector<E>    extends AbstractList<E>    implements List<E>, RandomAccess, Cloneable, java.io.Serializable{    protected Object[] elementData;//向量的大小大于其容量时,容量自动增加的量    protected int elementCount;// Vector对象中的有效组件数。    protected int capacityIncrement;//向量的大小大于其容量时,容量自动增加的量    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);    }    public Vector() {//构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零        this(10);    }    public Vector(Collection<? extends E> c) {//使用指定的初始容量和容量增量构造一个空的向量        elementData = c.toArray();//初始化elementCount        elementCount = elementData.length;//元素个数        // c.toArray might (incorrectly) not return Object[] (see 6260652)        if (elementData.getClass() != Object[].class)            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);    }    public synchronized void copyInto(Object[] anArray) {//将此向量的组件复制到指定的数组中。浅复制        System.arraycopy(elementData, 0, anArray, 0, elementCount);    }    public synchronized void trimToSize() {//对此向量的容量进行微调,使其等于向量的当前大小        modCount++;//修改次数加1        int oldCapacity = elementData.length;//数组的长度        if (elementCount < oldCapacity) {//实际元素个数与数组长度相比            elementData = Arrays.copyOf(elementData, elementCount);        }    }    public synchronized void ensureCapacity(int minCapacity) {//增加此向量的容量        if (minCapacity > 0) {            modCount++;//修改次数加1            ensureCapacityHelper(minCapacity);        }    }    private void ensureCapacityHelper(int minCapacity) {        // overflow-conscious code        if (minCapacity - elementData.length > 0)//是否增加            grow(minCapacity);    }    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    private void grow(int minCapacity) {        // overflow-conscious code        int oldCapacity = elementData.length;      //增加capacityIncrement容量(capacityIncrement大于0),否则为原来的扩充一倍        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;    }    public synchronized void setSize(int newSize) {//设置此向量的大小        modCount++;//操作次数加1        if (newSize > elementCount) {        //如果新大小小于当前大小,则丢弃索引 newSize处及其之后的所有项            ensureCapacityHelper(newSize);        } else {        //如果新大小大于当前大小,则会在向量的末尾添加相应数量的 null 项            for (int i = newSize ; i < elementCount ; i++) {                elementData[i] = null;            }        }        elementCount = newSize;    }    public synchronized int capacity() {//返回此向量的当前容量        return elementData.length;    }    public synchronized int size() {//返回此向量中的组件数,实际元素个数        return elementCount;    }    public synchronized boolean isEmpty() {//测试此向量是否不包含组件        return elementCount == 0;    }    public Enumeration<E> elements() {//返回此向量的组件的枚举。返回的 Enumeration 对象将生成此向量中的所有项        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");            }        };    }    public boolean contains(Object o) {//包含指定的元素        return indexOf(o, 0) >= 0;    }    public int indexOf(Object o) {//返回此向量中第一次出现的指定元素的索引        return indexOf(o, 0);    }  //返回此向量中第一次出现的指定元素的索引,从 index 处正向搜索,如果未找到该元素,则返回 -1    public synchronized int indexOf(Object o, int index) {        if (o == null) {            for (int i = index ; i < elementCount ; i++)//从index处开始搜索                if (elementData[i]==null)                    return i;        } else {            for (int i = index ; i < elementCount ; i++)                if (o.equals(elementData[i]))                    return i;        }        return -1;    }    //返回此向量中最后一次出现的指定元素的索引;如果此向量不包含该元素,则返回 -1    public synchronized int lastIndexOf(Object o) {        return lastIndexOf(o, elementCount-1);    }    //返回此向量中最后一次出现的指定元素的索引,从 index 处逆向搜索,如果未找到该元素,则返回 -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--)//从index处开始逆向搜索                if (elementData[i]==null)                    return i;        } else {            for (int i = index; i >= 0; i--)                if (o.equals(elementData[i]))                    return i;        }        return -1;    }    //返回指定索引处的组件。    public synchronized E elementAt(int index) {        if (index >= elementCount) {            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);        }        return elementData(index);    }    //返回此向量的第一个组件    public synchronized E firstElement() {        if (elementCount == 0) {            throw new NoSuchElementException();        }        return elementData(0);    }    //返回此向量的最后一个组件。    public synchronized E lastElement() {        if (elementCount == 0) {            throw new NoSuchElementException();        }        return elementData(elementCount - 1);    }    //将此向量指定 index处的组件设置为指定的对象    public synchronized void setElementAt(E obj, int index) {        if (index >= elementCount) {            throw new ArrayIndexOutOfBoundsException(index + " >= " +                                                     elementCount);        }        elementData[index] = obj;//直接修改    }    //删除指定索引处的组件    public synchronized void removeElementAt(int index) {        modCount++;//修改次数加1        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--;//个数减1        elementData[elementCount] = null; //方便GC回收    }    //将指定对象作为此向量中的组件插入到指定的 index 处    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;        elementCount++;    }    //将指定的组件添加到此向量的末尾    public synchronized void addElement(E obj) {        modCount++;        ensureCapacityHelper(elementCount + 1);        elementData[elementCount++] = obj;//将其大小增加 1    }    //从此向量中移除变量的第一个(索引最小的)匹配项    public synchronized boolean removeElement(Object obj) {        modCount++;        int i = indexOf(obj);        if (i >= 0) {            removeElementAt(i);            return true;        }        return false;    }    //清空    public synchronized void removeAllElements() {        modCount++;        // Let gc do its work        for (int i = 0; i < elementCount; i++)            elementData[i] = null;        elementCount = 0;    }    //返回向量的一个副本。浅复制    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();        }    }    //返回一个数组,包含此向量中以恰当顺序存放的所有元素    public synchronized Object[] toArray() {        return Arrays.copyOf(elementData, elementCount);    }    //返回一个数组,保留类型    @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;    }    //返回向量中指定位置的元素    @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);    }    //用指定的元素替换此向量中指定位置处的元素    public synchronized E set(int index, E element) {        if (index >= elementCount)            throw new ArrayIndexOutOfBoundsException(index);        E oldValue = elementData(index);        elementData[index] = element;        return oldValue;    }    //将指定元素添加到此向量的末尾。    public synchronized boolean add(E e) {        modCount++;        ensureCapacityHelper(elementCount + 1);        elementData[elementCount++] = e;        return true;    }    //移除此向量中指定元素的第一个匹配项    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;    }    //清空    public void clear() {        removeAllElements();    }    // Bulk Operations    //包含指定 Collection 中的所有元素    public synchronized boolean containsAll(Collection<?> c) {        return super.containsAll(c);    }    //将指定 Collection 中的所有元素添加到此向量的末尾    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;    }   //从此向量中移除包含在指定 Collection中的所有元素    public synchronized boolean removeAll(Collection<?> c) {        return super.removeAll(c);    }    //在此向量中仅保留包含在指定 Collection 中的元素    public synchronized boolean retainAll(Collection<?> c) {        return super.retainAll(c);    }    //在指定位置将指定 Collection 中的所有元素插入到此向量中    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);        System.arraycopy(a, 0, elementData, index, numNew);        elementCount += numNew;        return numNew != 0;    }    //比较指定对象与此向量的相等性    public synchronized boolean equals(Object o) {        return super.equals(o);    }    //返回此向量的哈希码值    public synchronized int hashCode() {        return super.hashCode();    }    //返回此向量的字符串表示形式    public synchronized String toString() {        return super.toString();    }    //返回此 List的部分视图,元素范围为从 fromIndex(包括)到 toIndex(不包括)。(    public synchronized List<E> subList(int fromIndex, int toIndex) {        return Collections.synchronizedList(super.subList(fromIndex, toIndex),                                            this);    }    //从此 List 中移除其索引位于 fromIndex(包括)与 toIndex(不包括)之间的所有元素    protected synchronized void removeRange(int fromIndex, int toIndex) {        modCount++;        int numMoved = elementCount - toIndex;        System.arraycopy(elementData, toIndex, elementData, fromIndex,                         numMoved);        // Let gc do its work        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();    }    //双向迭代器,index处开始    public synchronized ListIterator<E> listIterator(int index) {        if (index < 0 || index > elementCount)            throw new IndexOutOfBoundsException("Index: "+index);        return new ListItr(index);    }    //双向迭代器    public synchronized ListIterator<E> listIterator() {        return new ListItr(0);    }    //迭代器    public synchronized Iterator<E> iterator() {        return new 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() {            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;        }        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }    //双向迭代器内部实现    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;        }    }}

  StackStack类表示后进先出(LIFO)的对象堆栈它通过五个操作对类 Vector进行了扩展,允许将向量视为堆栈。Deque接口及其实现提供了更完整和更一致的LIFO堆栈操作,应该优先使用其实现,而非此类。例如:

Deque<Integer> stack = new ArrayDeque<Integer>();

//堆栈 先进后出(LIFO),继承Vector类并进行了扩展 ,允许将向量视为堆栈    public class Stack<E> extends Vector<E> {//JDK1.7         java.util    public Stack() {//创建一个空堆栈    }    //把项压入堆栈顶部。其作用与下面的方法完全相同    public E push(E item) {        addElement(item);        return item;    }    //移除堆栈顶部的对象,并作为此函数的值返回该对象    public synchronized E pop() {        E       obj;        int     len = size();        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为基数    public synchronized int search(Object o) {        int i = lastIndexOf(o);        if (i >= 0) {            return size() - i;        }        return -1;    }    private static final long serialVersionUID = 1224463164541339165L;}

0 0
原创粉丝点击