【java】【java collection】Vector

来源:互联网 发布:桔子酒店 知乎 编辑:程序博客网 时间:2024/05/16 00:26

学习vector请看官方API

https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html

学习参考资料

http://www.cnblogs.com/skywang12345/p/3308833.html

学习vector请看源代码   自己还没有全部看完 看了一大半 还有后面一部分没有看完

/*//底层通过数组实现  原始容量为10  增加系数可是自己定或者直接两倍The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index.However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.//迭代器 只能是自己add remove等不会报异常 对于其他其他迭代器修改的就是会报错  //Enumerations就不会报错 即便是有别的线程对其进行修改  看两者的源代码就知道了 //迭代器  每次都是会有一个 checkForComodification();  就是去判断modcount是否等于expectedcount 这点可以去fail-fast文章去看更详细的内容The iterators returned by this class's iterator and listIterator methods are fail-fast: if the vector is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. The Enumerations returned by the elements method are not fail-fast.//fail-fast不能是能够报异常的 只能是尽最大能力去报错Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.*/



public class Vector<E>    extends AbstractList<E>    implements List<E>, RandomAccess, Cloneable, java.io.Serializable{   //保存vector中数据的数组    protected Object[] elementData;   //数组元素数量    protected int elementCount;    //容量增长系数  如果小于等于0  则每次数组容量都增加为原来的两倍    protected int capacityIncrement;    //Vector版本序列号    private static final long serialVersionUID = -2767605614048989439L;    //默认容量为10    public Vector() {        this(10);    }    //指定vector容量大小的构造函数    public Vector(int initialCapacity) {        this(initialCapacity, 0);    }    //指定Vector容量大小和增长系数的构造函数    public Vector(int initialCapacity, int capacityIncrement) {        super();//调用抽象类AbstractList默认构造函数        if (initialCapacity < 0)            throw new IllegalArgumentException("Illegal Capacity: "+                                               initialCapacity);        this.elementData = new Object[initialCapacity];        this.capacityIncrement = capacityIncrement;    }   //指定集合的Vector的构造函数    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的全部元素都拷贝到数组anArray中    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);        }    }    //调整数组长度       public synchronized void setSize(int newSize) {        modCount++;        if (newSize > elementCount) {            ensureCapacityHelper(newSize);        } else {            //如果比原来的数组长度小 就需要将其后面的元素设置成null            for (int i = newSize ; i < elementCount ; i++) {                elementData[i] = null;            }        }        elementCount = newSize;    }   //确定数组长度是否需要增加    public synchronized void ensureCapacity(int minCapacity) {        if (minCapacity > 0) {            modCount++;            ensureCapacityHelper(minCapacity);        }    }    private void ensureCapacityHelper(int minCapacity) {        //当现有数组长度小于我们最小要求数的时候 就需要增加数组长度        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;        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)             throw new OutOfMemoryError();        return (minCapacity > MAX_ARRAY_SIZE) ?            Integer.MAX_VALUE :            MAX_ARRAY_SIZE;    }    //返回数组总长度    public synchronized int capacity() {        return elementData.length;    }    //返回数组当前元素个数    public synchronized int size() {        return elementCount;    }    //判断Vector是否为空    public synchronized boolean isEmpty() {        return elementCount == 0;    }    //返回Vector中全部元素对应的Enumeration    public Enumeration<E> elements() {        return new Enumeration<E>() {//通过匿名类实现Enumeration            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");            }        };    }    //从index位置开始判断是否有对象o  需要分别对象o是否为null    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;    }    public int indexOf(Object o) {        return indexOf(o, 0);    }    //返回元素中是否包含对象o    public boolean contains(Object o) {        return indexOf(o, 0) >= 0;    }   //相比较于前面indexof 这里的lastindexof是从后面往前面遍历  对象o也是需要判断是否为null 两种情况进行遍历查找    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;    }    public synchronized int lastIndexOf(Object o) {        return lastIndexOf(o, elementCount-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);    }    //和上面的第一个、最后一个元素 都是需要考虑边界情况    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++;  //删除元素属于结构性修改        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--;//元素个数减一        //记得将最后一个元素设置成null  能够gc        elementData[elementCount] = null; /* to let gc do its work */    }       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++;//减少的时候需要让gc能够去回收  即设置成null    }    //同样是增加元素 但是需要注意是否有返回值    public synchronized void addElement(E obj) {        modCount++;        ensureCapacityHelper(elementCount + 1);        elementData[elementCount++] = obj;    }     public synchronized boolean add(E e) {        modCount++;        ensureCapacityHelper(elementCount + 1);        elementData[elementCount++] = e;        return true;    }    public void add(int index, E element) {        insertElementAt(element, index);    }    public synchronized boolean removeElement(Object obj) {        modCount++;        int i = indexOf(obj);//首先判断对象中是否有其元素        if (i >= 0) {            removeElementAt(i);            return true;        }        return false;    }    public boolean remove(Object o) {        return removeElement(o);    }    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;    }  //在java中 移除数组所有元素 只需要将其内容设置成null即可    public synchronized void removeAllElements() {        modCount++;        // Let gc do its work        for (int i = 0; i < elementCount; i++)            elementData[i] = null;        elementCount = 0;    }    public void clear() {        removeAllElements();    }    //克隆函数    public synchronized Object clone() {        try {            @SuppressWarnings("unchecked")                Vector<E> v = (Vector<E>) super.clone();                //// 将当前Vector的全部元素拷贝到v中            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);        }    }    //返回Object数组    public synchronized Object[] toArray() {        return Arrays.copyOf(elementData, elementCount);    }    // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型    @SuppressWarnings("unchecked")    public synchronized <T> T[] toArray(T[] a) {        // 若数组a的大小 < Vector的元素个数        // 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中        if (a.length < elementCount)            return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());                // 若数组a的大小 >= Vector的元素个数;        // 则将Vector的全部元素都拷贝到数组a中        System.arraycopy(elementData, 0, a, 0, elementCount);        //如果是超出的部分 后面数组内容设置为null          if (a.length > elementCount)            a[elementCount] = null;//好像只需要设置后面第一个元素值为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);    }   //set注意是有返回值的  返回旧位置上面的元素值    public synchronized E set(int index, E element) {        if (index >= elementCount)            throw new ArrayIndexOutOfBoundsException(index);        E oldValue = elementData(index);        elementData[index] = element;        return oldValue;    }        // Bulk Operations  批量操作    /*    抽象类AbstractCollection  containsAll源代码    public boolean containsAll(Collection<?> c) {        for (Object e : c)            if (!contains(e))                return false;        return true;    }     */    public synchronized boolean containsAll(Collection<?> c) {        return super.containsAll(c);    }    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);//将数组a的内容全部加到数组elementData的后面        elementCount += numNew;        return numNew != 0; //如果没有添加新元素 则返回false    }   /*    Objects中的源代码    public static <T> T requireNonNull(T obj) {        if (obj == null)            throw new NullPointerException();        return obj;    }    //将elementData中所有数组c的元素全部删除  如果有元素删除 那么返回true  反之false    public boolean removeAll(Collection<?> c) {        Objects.requireNonNull(c);        boolean modified = false;        Iterator<?> it = iterator();        while (it.hasNext()) {            if (c.contains(it.next())) {                it.remove();                modified = true;            }        }        return modified;    }   */    public synchronized boolean removeAll(Collection<?> c) {        return super.removeAll(c);    }        /*    public boolean retainAll(Collection<?> c) {        Objects.requireNonNull(c);        boolean modified = false;        Iterator<E> it = iterator();        while (it.hasNext()) {            if (!c.contains(it.next())) {   //只保留和c中数组一样元素内容                it.remove();                modified = true;            }        }        return modified;    }    */    public synchronized boolean retainAll(Collection<?> c) {        return super.retainAll(c);    }        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;    }    /**     * Compares the specified Object with this Vector for equality.  Returns     * true if and only if the specified Object is also a List, both Lists     * have the same size, and all corresponding pairs of elements in the two     * Lists are <em>equal</em>.  (Two elements {@code e1} and     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :     * e1.equals(e2))}.)  In other words, two Lists are defined to be     * equal if they contain the same elements in the same order.     *     * @param o the Object to be compared for equality with this Vector     * @return true if the specified Object is equal to this Vector     */    public synchronized boolean equals(Object o) {        return super.equals(o);    }   /*        抽象类的AbstractList  hashcode函数        public int hashCode() {            int hashCode = 1;            for (E e : this)                hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());            return hashCode;        }   */    public synchronized int hashCode() {        return super.hashCode();    }    /*     抽象类的AbstractList  toString()函数     public String toString() {        Iterator<E> it = iterator();        if (! it.hasNext())            return "[]";        StringBuilder sb = new StringBuilder();        sb.append('[');        for (;;) {            E e = it.next();            sb.append(e == this ? "(this Collection)" : e);            if (! it.hasNext())                return sb.append(']').toString();            sb.append(',').append(' ');        }    }    */    public synchronized String toString() {        return super.toString();    }   //子数组    public synchronized List<E> subList(int fromIndex, int toIndex) {        return Collections.synchronizedList(super.subList(fromIndex, toIndex),                                            this);    }    /**     * Removes from this list all of the elements whose index is between     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.     * Shifts any succeeding elements to the left (reduces their index).     * This call shortens the list by {@code (toIndex - fromIndex)} elements.     * (If {@code toIndex==fromIndex}, this operation has no effect.)     */    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;    }    /**     * Save the state of the {@code Vector} instance to a stream (that     * is, serialize it).     * This method performs synchronization to ensure the consistency     * of the serialized data.     */    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();    }    /**     * Returns a list iterator over the elements in this list (in proper     * sequence), starting at the specified position in the list.     * The specified index indicates the first element that would be     * returned by an initial call to {@link ListIterator#next next}.     * An initial call to {@link ListIterator#previous previous} would     * return the element with the specified index minus one.     *     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.     *     * @throws IndexOutOfBoundsException {@inheritDoc}     */    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).     *     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.     *     * @see #listIterator(int)     */    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;        }    }}

遍历方式

package Tree;import java.util.*;public class VectorRandomAccessTest {    public static void main(String[] args) {        Vector vec= new Vector();        for (int i=0; i<100000; i++)            vec.add(i);        iteratorThroughRandomAccess(vec) ;//随机访问形式  get        iteratorThroughIterator(vec) ;//迭代器        iteratorThroughFor2(vec) ;//for循环        iteratorThroughEnumeration(vec) ;//Enumeration    }    public static void iteratorThroughRandomAccess(List list) {        long startTime;        long endTime;        startTime = System.currentTimeMillis();        for (int i=0; i<list.size(); i++) {            list.get(i);        }        endTime = System.currentTimeMillis();        long interval = endTime - startTime;        System.out.println("iteratorThroughRandomAccess:" + interval+" ms");    }    public static void iteratorThroughIterator(List list) {        long startTime;        long endTime;        startTime = System.currentTimeMillis();        for(Iterator iter = list.iterator(); iter.hasNext(); ) {            iter.next();        }        endTime = System.currentTimeMillis();        long interval = endTime - startTime;        System.out.println("iteratorThroughIterator:" + interval+" ms");    }    public static void iteratorThroughFor2(List list) {        long startTime;        long endTime;        startTime = System.currentTimeMillis();        for(Object obj:list)            ;        endTime = System.currentTimeMillis();        long interval = endTime - startTime;        System.out.println("iteratorThroughFor2:" + interval+" ms");    }    public static void iteratorThroughEnumeration(Vector vec) {        long startTime;        long endTime;        startTime = System.currentTimeMillis();        for(Enumeration enu = vec.elements(); enu.hasMoreElements(); ) {            enu.nextElement();        }        endTime = System.currentTimeMillis();        long interval = endTime - startTime;        System.out.println("iteratorThroughEnumeration:" + interval+" ms");    }}

使用示例

package Test;import java.util.Vector;import java.util.Enumeration;public class VectorTest {    public static void main(String[] args) {        // 新建Vector        Vector vec = new Vector();        // 添加元素        vec.add("1");        vec.add("2");        vec.add("3");        vec.add("4");        vec.add("5");        // 设置第一个元素为100        vec.set(0, "100");        // 将“500”插入到第3个位置        vec.add(2, "300");        System.out.println("vec:"+vec);        // (顺序查找)获取100的索引        System.out.println("vec.indexOf(100):"+vec.indexOf("100"));        // (倒序查找)获取100的索引        System.out.println("vec.lastIndexOf(100):"+vec.lastIndexOf("100"));        // 获取第一个元素        System.out.println("vec.firstElement():"+vec.firstElement());        // 获取第3个元素        System.out.println("vec.elementAt(2):"+vec.elementAt(2));        // 获取最后一个元素        System.out.println("vec.lastElement():"+vec.lastElement());        // 获取Vector的大小        System.out.println("size:"+vec.size());        // 获取Vector的总的容量        System.out.println("capacity:"+vec.capacity());        // 获取vector的“第2”到“第4”个元素        System.out.println("vec 2 to 4:"+vec.subList(1, 4));        // 通过Enumeration遍历Vector        Enumeration enu = vec.elements();        while(enu.hasMoreElements())            System.out.println("nextElement():"+enu.nextElement());        Vector retainVec = new Vector();        retainVec.add("100");        retainVec.add("300");        // 获取“vec”中包含在“retainVec中的元素”的集合        System.out.println("vec.retain():"+vec.retainAll(retainVec));        System.out.println("vec:"+vec);        // 获取vec对应的String数组        String[] arr = (String[]) vec.toArray(new String[0]);        for (String str:arr)            System.out.println("str:"+str);        // 清空Vector clear()和removeAllElements()一样!         vec.clear();        //vec.removeAllElements();        // 判断Vector是否为空        System.out.println("vec.isEmpty():"+vec.isEmpty());    }}

迭代器异常

package Test;import java.util.Iterator;import java.util.Vector;public class FailFastTest {    private static Vector<Integer> vector = new Vector<>();    private static class threadOne extends Thread{        public void run() {            Iterator<Integer> iterator = vector.iterator();            while(iterator.hasNext()){                int i = iterator.next();//                if (i==3){//                    iterator.remove();//自身迭代器去修改的时候就是可以的  不会报错//                }else{//                    System.out.println("ThreadOne 遍历:" + i);//                }                System.out.println("ThreadOne 遍历:" + i);            }        }    }    private static class threadTwo extends Thread{        public void run(){            int i = 0 ;            while(i < 6){                System.out.println("ThreadTwo run:" + i);                if(i == 3){                    vector.remove(i);                }                i++;            }        }    }    public static void main(String[] args) {        for(int i = 0 ; i < 10;i++){            vector.add(i);        }        new threadOne().start();        new threadTwo().start();    }}

迭代器正常

package Test;import java.util.Iterator;import java.util.Vector;public class FailFastTest {    private static Vector<Integer> vector = new Vector<>();    private static class threadOne extends Thread{        public void run() {            Iterator<Integer> iterator = vector.iterator();            while(iterator.hasNext()){                int i = iterator.next();                if (i==3){                    iterator.remove();//自身迭代器去修改的时候就是可以的  不会报错                }else{                    System.out.println("ThreadOne 遍历:" + i);                }            }        }    }    public static void main(String[] args) {        for(int i = 0 ; i < 10;i++){            vector.add(i);        }        new threadOne().start();    }}


Enumeration正常  即便有其他的线程对其进行修改 还是不会报错 还是能够正常运行 输出最终的结果

package Test;import java.util.Enumeration;import java.util.Vector;public class FailFastTest {    private static Vector<Integer> vector = new Vector<>();    private static class threadOne extends Thread {        public void run() {            Enumeration enumeration = vector.elements();            while (enumeration.hasMoreElements()) {                try {                    Thread.sleep(100);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("Threadone run" + enumeration.nextElement());            }        }    }    private static class threadTwo extends Thread {        public void run() {            int i = 0;            while (i < 6) {                System.out.println("ThreadTwo run:" + i);                if (i == 3) {                    vector.remove(i);                }                i++;            }        }    }    public static void main(String[] args) {        for (int i = 0; i < 10; i++) {            vector.add(i);        }        new threadOne().start();        new threadTwo().start();    }}

"C:\Program Files\Java\jdk1.8.0_111\bin\java" -Didea.launcher.port=7535 "-Didea.launcher.bin.path=F:\win7\IntelliJ IDEA 2016.3.1\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_111\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_111\jre\lib\rt.jar;E:\untitled\out\production\untitled;F:\win7\IntelliJ IDEA 2016.3.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain Test.FailFastTestThreadTwo run:0ThreadTwo run:1ThreadTwo run:2ThreadTwo run:3ThreadTwo run:4ThreadTwo run:5Threadone run0Threadone run1Threadone run2Threadone run4Threadone run5Threadone run6Threadone run7Threadone run8Threadone run9Process finished with exit code 0




0 0
原创粉丝点击