1 /*
2  * Copyright (c) 1994, 2017, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 package java.util;
27 
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.StreamCorruptedException;
31 import java.util.function.Consumer;
32 import java.util.function.Predicate;
33 import java.util.function.UnaryOperator;
34 
35 /**
36  * The {@code Vector} class implements a growable array of
37  * objects. Like an array, it contains components that can be
38  * accessed using an integer index. However, the size of a
39  * {@code Vector} can grow or shrink as needed to accommodate
40  * adding and removing items after the {@code Vector} has been created.
41  *
42  * <p>Each vector tries to optimize storage management by maintaining a
43  * {@code capacity} and a {@code capacityIncrement}. The
44  * {@code capacity} is always at least as large as the vector
45  * size; it is usually larger because as components are added to the
46  * vector, the vector's storage increases in chunks the size of
47  * {@code capacityIncrement}. An application can increase the
48  * capacity of a vector before inserting a large number of
49  * components; this reduces the amount of incremental reallocation.
50  *
51  * <p><a name="fail-fast">
52  * The iterators returned by this class's {@link #iterator() iterator} and
53  * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em></a>:
54  * if the vector is structurally modified at any time after the iterator is
55  * created, in any way except through the iterator's own
56  * {@link ListIterator#remove() remove} or
57  * {@link ListIterator#add(Object) add} methods, the iterator will throw a
58  * {@link ConcurrentModificationException}.  Thus, in the face of
59  * concurrent modification, the iterator fails quickly and cleanly, rather
60  * than risking arbitrary, non-deterministic behavior at an undetermined
61  * time in the future.  The {@link Enumeration Enumerations} returned by
62  * the {@link #elements() elements} method are <em>not</em> fail-fast.
63  *
64  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
65  * as it is, generally speaking, impossible to make any hard guarantees in the
66  * presence of unsynchronized concurrent modification.  Fail-fast iterators
67  * throw {@code ConcurrentModificationException} on a best-effort basis.
68  * Therefore, it would be wrong to write a program that depended on this
69  * exception for its correctness:  <i>the fail-fast behavior of iterators
70  * should be used only to detect bugs.</i>
71  *
72  * <p>As of the Java 2 platform v1.2, this class was retrofitted to
73  * implement the {@link List} interface, making it a member of the
74  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
75  * Java Collections Framework</a>.  Unlike the new collection
76  * implementations, {@code Vector} is synchronized.  If a thread-safe
77  * implementation is not needed, it is recommended to use {@link
78  * ArrayList} in place of {@code Vector}.
79  *
80  * @author  Lee Boynton
81  * @author  Jonathan Payne
82  * @see Collection
83  * @see LinkedList
84  * @since   JDK1.0
85  */
86 public class Vector<E>
87     extends AbstractList<E>
88     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
89 {
90     /**
91      * The array buffer into which the components of the vector are
92      * stored. The capacity of the vector is the length of this array buffer,
93      * and is at least large enough to contain all the vector's elements.
94      *
95      * <p>Any array elements following the last element in the Vector are null.
96      *
97      * @serial
98      */
99     protected Object[] elementData;
100 
101     /**
102      * The number of valid components in this {@code Vector} object.
103      * Components {@code elementData[0]} through
104      * {@code elementData[elementCount-1]} are the actual items.
105      *
106      * @serial
107      */
108     protected int elementCount;
109 
110     /**
111      * The amount by which the capacity of the vector is automatically
112      * incremented when its size becomes greater than its capacity.  If
113      * the capacity increment is less than or equal to zero, the capacity
114      * of the vector is doubled each time it needs to grow.
115      *
116      * @serial
117      */
118     protected int capacityIncrement;
119 
120     /** use serialVersionUID from JDK 1.0.2 for interoperability */
121     private static final long serialVersionUID = -2767605614048989439L;
122 
123     /**
124      * Constructs an empty vector with the specified initial capacity and
125      * capacity increment.
126      *
127      * @param   initialCapacity     the initial capacity of the vector
128      * @param   capacityIncrement   the amount by which the capacity is
129      *                              increased when the vector overflows
130      * @throws IllegalArgumentException if the specified initial capacity
131      *         is negative
132      */
Vector(int initialCapacity, int capacityIncrement)133     public Vector(int initialCapacity, int capacityIncrement) {
134         super();
135         if (initialCapacity < 0)
136             throw new IllegalArgumentException("Illegal Capacity: "+
137                                                initialCapacity);
138         this.elementData = new Object[initialCapacity];
139         this.capacityIncrement = capacityIncrement;
140     }
141 
142     /**
143      * Constructs an empty vector with the specified initial capacity and
144      * with its capacity increment equal to zero.
145      *
146      * @param   initialCapacity   the initial capacity of the vector
147      * @throws IllegalArgumentException if the specified initial capacity
148      *         is negative
149      */
Vector(int initialCapacity)150     public Vector(int initialCapacity) {
151         this(initialCapacity, 0);
152     }
153 
154     /**
155      * Constructs an empty vector so that its internal data array
156      * has size {@code 10} and its standard capacity increment is
157      * zero.
158      */
Vector()159     public Vector() {
160         this(10);
161     }
162 
163     /**
164      * Constructs a vector containing the elements of the specified
165      * collection, in the order they are returned by the collection's
166      * iterator.
167      *
168      * @param c the collection whose elements are to be placed into this
169      *       vector
170      * @throws NullPointerException if the specified collection is null
171      * @since   1.2
172      */
Vector(Collection<? extends E> c)173     public Vector(Collection<? extends E> c) {
174         Object[] a = c.toArray();
175         elementCount = a.length;
176         if (c.getClass() == ArrayList.class) {
177             elementData = a;
178         } else {
179             elementData = Arrays.copyOf(a, elementCount, Object[].class);
180         }
181     }
182 
183     /**
184      * Copies the components of this vector into the specified array.
185      * The item at index {@code k} in this vector is copied into
186      * component {@code k} of {@code anArray}.
187      *
188      * @param  anArray the array into which the components get copied
189      * @throws NullPointerException if the given array is null
190      * @throws IndexOutOfBoundsException if the specified array is not
191      *         large enough to hold all the components of this vector
192      * @throws ArrayStoreException if a component of this vector is not of
193      *         a runtime type that can be stored in the specified array
194      * @see #toArray(Object[])
195      */
copyInto(Object[] anArray)196     public synchronized void copyInto(Object[] anArray) {
197         System.arraycopy(elementData, 0, anArray, 0, elementCount);
198     }
199 
200     /**
201      * Trims the capacity of this vector to be the vector's current
202      * size. If the capacity of this vector is larger than its current
203      * size, then the capacity is changed to equal the size by replacing
204      * its internal data array, kept in the field {@code elementData},
205      * with a smaller one. An application can use this operation to
206      * minimize the storage of a vector.
207      */
trimToSize()208     public synchronized void trimToSize() {
209         modCount++;
210         int oldCapacity = elementData.length;
211         if (elementCount < oldCapacity) {
212             elementData = Arrays.copyOf(elementData, elementCount);
213         }
214     }
215 
216     /**
217      * Increases the capacity of this vector, if necessary, to ensure
218      * that it can hold at least the number of components specified by
219      * the minimum capacity argument.
220      *
221      * <p>If the current capacity of this vector is less than
222      * {@code minCapacity}, then its capacity is increased by replacing its
223      * internal data array, kept in the field {@code elementData}, with a
224      * larger one.  The size of the new data array will be the old size plus
225      * {@code capacityIncrement}, unless the value of
226      * {@code capacityIncrement} is less than or equal to zero, in which case
227      * the new capacity will be twice the old capacity; but if this new size
228      * is still smaller than {@code minCapacity}, then the new capacity will
229      * be {@code minCapacity}.
230      *
231      * @param minCapacity the desired minimum capacity
232      */
ensureCapacity(int minCapacity)233     public synchronized void ensureCapacity(int minCapacity) {
234         if (minCapacity > 0) {
235             modCount++;
236             ensureCapacityHelper(minCapacity);
237         }
238     }
239 
240     /**
241      * This implements the unsynchronized semantics of ensureCapacity.
242      * Synchronized methods in this class can internally call this
243      * method for ensuring capacity without incurring the cost of an
244      * extra synchronization.
245      *
246      * @see #ensureCapacity(int)
247      */
ensureCapacityHelper(int minCapacity)248     private void ensureCapacityHelper(int minCapacity) {
249         // overflow-conscious code
250         if (minCapacity - elementData.length > 0)
251             grow(minCapacity);
252     }
253 
254     /**
255      * The maximum size of array to allocate.
256      * Some VMs reserve some header words in an array.
257      * Attempts to allocate larger arrays may result in
258      * OutOfMemoryError: Requested array size exceeds VM limit
259      */
260     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
261 
grow(int minCapacity)262     private void grow(int minCapacity) {
263         // overflow-conscious code
264         int oldCapacity = elementData.length;
265         int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
266                                          capacityIncrement : oldCapacity);
267         if (newCapacity - minCapacity < 0)
268             newCapacity = minCapacity;
269         if (newCapacity - MAX_ARRAY_SIZE > 0)
270             newCapacity = hugeCapacity(minCapacity);
271         elementData = Arrays.copyOf(elementData, newCapacity);
272     }
273 
hugeCapacity(int minCapacity)274     private static int hugeCapacity(int minCapacity) {
275         if (minCapacity < 0) // overflow
276             throw new OutOfMemoryError();
277         return (minCapacity > MAX_ARRAY_SIZE) ?
278             Integer.MAX_VALUE :
279             MAX_ARRAY_SIZE;
280     }
281 
282     /**
283      * Sets the size of this vector. If the new size is greater than the
284      * current size, new {@code null} items are added to the end of
285      * the vector. If the new size is less than the current size, all
286      * components at index {@code newSize} and greater are discarded.
287      *
288      * @param  newSize   the new size of this vector
289      * @throws ArrayIndexOutOfBoundsException if the new size is negative
290      */
setSize(int newSize)291     public synchronized void setSize(int newSize) {
292         modCount++;
293         if (newSize > elementCount) {
294             ensureCapacityHelper(newSize);
295         } else {
296             for (int i = newSize ; i < elementCount ; i++) {
297                 elementData[i] = null;
298             }
299         }
300         elementCount = newSize;
301     }
302 
303     /**
304      * Returns the current capacity of this vector.
305      *
306      * @return  the current capacity (the length of its internal
307      *          data array, kept in the field {@code elementData}
308      *          of this vector)
309      */
capacity()310     public synchronized int capacity() {
311         return elementData.length;
312     }
313 
314     /**
315      * Returns the number of components in this vector.
316      *
317      * @return  the number of components in this vector
318      */
size()319     public synchronized int size() {
320         return elementCount;
321     }
322 
323     /**
324      * Tests if this vector has no components.
325      *
326      * @return  {@code true} if and only if this vector has
327      *          no components, that is, its size is zero;
328      *          {@code false} otherwise.
329      */
isEmpty()330     public synchronized boolean isEmpty() {
331         return elementCount == 0;
332     }
333 
334     /**
335      * Returns an enumeration of the components of this vector. The
336      * returned {@code Enumeration} object will generate all items in
337      * this vector. The first item generated is the item at index {@code 0},
338      * then the item at index {@code 1}, and so on.
339      *
340      * @return  an enumeration of the components of this vector
341      * @see     Iterator
342      */
elements()343     public Enumeration<E> elements() {
344         return new Enumeration<E>() {
345             int count = 0;
346 
347             public boolean hasMoreElements() {
348                 return count < elementCount;
349             }
350 
351             public E nextElement() {
352                 synchronized (Vector.this) {
353                     if (count < elementCount) {
354                         return elementData(count++);
355                     }
356                 }
357                 throw new NoSuchElementException("Vector Enumeration");
358             }
359         };
360     }
361 
362     /**
363      * Returns {@code true} if this vector contains the specified element.
364      * More formally, returns {@code true} if and only if this vector
365      * contains at least one element {@code e} such that
366      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
367      *
368      * @param o element whose presence in this vector is to be tested
369      * @return {@code true} if this vector contains the specified element
370      */
contains(Object o)371     public boolean contains(Object o) {
372         return indexOf(o, 0) >= 0;
373     }
374 
375     /**
376      * Returns the index of the first occurrence of the specified element
377      * in this vector, or -1 if this vector does not contain the element.
378      * More formally, returns the lowest index {@code i} such that
379      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
380      * or -1 if there is no such index.
381      *
382      * @param o element to search for
383      * @return the index of the first occurrence of the specified element in
384      *         this vector, or -1 if this vector does not contain the element
385      */
indexOf(Object o)386     public int indexOf(Object o) {
387         return indexOf(o, 0);
388     }
389 
390     /**
391      * Returns the index of the first occurrence of the specified element in
392      * this vector, searching forwards from {@code index}, or returns -1 if
393      * the element is not found.
394      * More formally, returns the lowest index {@code i} such that
395      * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
396      * or -1 if there is no such index.
397      *
398      * @param o element to search for
399      * @param index index to start searching from
400      * @return the index of the first occurrence of the element in
401      *         this vector at position {@code index} or later in the vector;
402      *         {@code -1} if the element is not found.
403      * @throws IndexOutOfBoundsException if the specified index is negative
404      * @see     Object#equals(Object)
405      */
indexOf(Object o, int index)406     public synchronized int indexOf(Object o, int index) {
407         if (o == null) {
408             for (int i = index ; i < elementCount ; i++)
409                 if (elementData[i]==null)
410                     return i;
411         } else {
412             for (int i = index ; i < elementCount ; i++)
413                 if (o.equals(elementData[i]))
414                     return i;
415         }
416         return -1;
417     }
418 
419     /**
420      * Returns the index of the last occurrence of the specified element
421      * in this vector, or -1 if this vector does not contain the element.
422      * More formally, returns the highest index {@code i} such that
423      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
424      * or -1 if there is no such index.
425      *
426      * @param o element to search for
427      * @return the index of the last occurrence of the specified element in
428      *         this vector, or -1 if this vector does not contain the element
429      */
lastIndexOf(Object o)430     public synchronized int lastIndexOf(Object o) {
431         return lastIndexOf(o, elementCount-1);
432     }
433 
434     /**
435      * Returns the index of the last occurrence of the specified element in
436      * this vector, searching backwards from {@code index}, or returns -1 if
437      * the element is not found.
438      * More formally, returns the highest index {@code i} such that
439      * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
440      * or -1 if there is no such index.
441      *
442      * @param o element to search for
443      * @param index index to start searching backwards from
444      * @return the index of the last occurrence of the element at position
445      *         less than or equal to {@code index} in this vector;
446      *         -1 if the element is not found.
447      * @throws IndexOutOfBoundsException if the specified index is greater
448      *         than or equal to the current size of this vector
449      */
lastIndexOf(Object o, int index)450     public synchronized int lastIndexOf(Object o, int index) {
451         if (index >= elementCount)
452             throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
453 
454         if (o == null) {
455             for (int i = index; i >= 0; i--)
456                 if (elementData[i]==null)
457                     return i;
458         } else {
459             for (int i = index; i >= 0; i--)
460                 if (o.equals(elementData[i]))
461                     return i;
462         }
463         return -1;
464     }
465 
466     /**
467      * Returns the component at the specified index.
468      *
469      * <p>This method is identical in functionality to the {@link #get(int)}
470      * method (which is part of the {@link List} interface).
471      *
472      * @param      index   an index into this vector
473      * @return     the component at the specified index
474      * @throws ArrayIndexOutOfBoundsException if the index is out of range
475      *         ({@code index < 0 || index >= size()})
476      */
elementAt(int index)477     public synchronized E elementAt(int index) {
478         if (index >= elementCount) {
479             throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
480         }
481 
482         return elementData(index);
483     }
484 
485     /**
486      * Returns the first component (the item at index {@code 0}) of
487      * this vector.
488      *
489      * @return     the first component of this vector
490      * @throws NoSuchElementException if this vector has no components
491      */
firstElement()492     public synchronized E firstElement() {
493         if (elementCount == 0) {
494             throw new NoSuchElementException();
495         }
496         return elementData(0);
497     }
498 
499     /**
500      * Returns the last component of the vector.
501      *
502      * @return  the last component of the vector, i.e., the component at index
503      *          <code>size()&nbsp;-&nbsp;1</code>.
504      * @throws NoSuchElementException if this vector is empty
505      */
lastElement()506     public synchronized E lastElement() {
507         if (elementCount == 0) {
508             throw new NoSuchElementException();
509         }
510         return elementData(elementCount - 1);
511     }
512 
513     /**
514      * Sets the component at the specified {@code index} of this
515      * vector to be the specified object. The previous component at that
516      * position is discarded.
517      *
518      * <p>The index must be a value greater than or equal to {@code 0}
519      * and less than the current size of the vector.
520      *
521      * <p>This method is identical in functionality to the
522      * {@link #set(int, Object) set(int, E)}
523      * method (which is part of the {@link List} interface). Note that the
524      * {@code set} method reverses the order of the parameters, to more closely
525      * match array usage.  Note also that the {@code set} method returns the
526      * old value that was stored at the specified position.
527      *
528      * @param      obj     what the component is to be set to
529      * @param      index   the specified index
530      * @throws ArrayIndexOutOfBoundsException if the index is out of range
531      *         ({@code index < 0 || index >= size()})
532      */
setElementAt(E obj, int index)533     public synchronized void setElementAt(E obj, int index) {
534         if (index >= elementCount) {
535             throw new ArrayIndexOutOfBoundsException(index + " >= " +
536                                                      elementCount);
537         }
538         elementData[index] = obj;
539     }
540 
541     /**
542      * Deletes the component at the specified index. Each component in
543      * this vector with an index greater or equal to the specified
544      * {@code index} is shifted downward to have an index one
545      * smaller than the value it had previously. The size of this vector
546      * is decreased by {@code 1}.
547      *
548      * <p>The index must be a value greater than or equal to {@code 0}
549      * and less than the current size of the vector.
550      *
551      * <p>This method is identical in functionality to the {@link #remove(int)}
552      * method (which is part of the {@link List} interface).  Note that the
553      * {@code remove} method returns the old value that was stored at the
554      * specified position.
555      *
556      * @param      index   the index of the object to remove
557      * @throws ArrayIndexOutOfBoundsException if the index is out of range
558      *         ({@code index < 0 || index >= size()})
559      */
removeElementAt(int index)560     public synchronized void removeElementAt(int index) {
561         modCount++;
562         if (index >= elementCount) {
563             throw new ArrayIndexOutOfBoundsException(index + " >= " +
564                                                      elementCount);
565         }
566         else if (index < 0) {
567             throw new ArrayIndexOutOfBoundsException(index);
568         }
569         int j = elementCount - index - 1;
570         if (j > 0) {
571             System.arraycopy(elementData, index + 1, elementData, index, j);
572         }
573         elementCount--;
574         elementData[elementCount] = null; /* to let gc do its work */
575     }
576 
577     /**
578      * Inserts the specified object as a component in this vector at the
579      * specified {@code index}. Each component in this vector with
580      * an index greater or equal to the specified {@code index} is
581      * shifted upward to have an index one greater than the value it had
582      * previously.
583      *
584      * <p>The index must be a value greater than or equal to {@code 0}
585      * and less than or equal to the current size of the vector. (If the
586      * index is equal to the current size of the vector, the new element
587      * is appended to the Vector.)
588      *
589      * <p>This method is identical in functionality to the
590      * {@link #add(int, Object) add(int, E)}
591      * method (which is part of the {@link List} interface).  Note that the
592      * {@code add} method reverses the order of the parameters, to more closely
593      * match array usage.
594      *
595      * @param      obj     the component to insert
596      * @param      index   where to insert the new component
597      * @throws ArrayIndexOutOfBoundsException if the index is out of range
598      *         ({@code index < 0 || index > size()})
599      */
insertElementAt(E obj, int index)600     public synchronized void insertElementAt(E obj, int index) {
601         modCount++;
602         if (index > elementCount) {
603             throw new ArrayIndexOutOfBoundsException(index
604                                                      + " > " + elementCount);
605         }
606         ensureCapacityHelper(elementCount + 1);
607         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
608         elementData[index] = obj;
609         elementCount++;
610     }
611 
612     /**
613      * Adds the specified component to the end of this vector,
614      * increasing its size by one. The capacity of this vector is
615      * increased if its size becomes greater than its capacity.
616      *
617      * <p>This method is identical in functionality to the
618      * {@link #add(Object) add(E)}
619      * method (which is part of the {@link List} interface).
620      *
621      * @param   obj   the component to be added
622      */
addElement(E obj)623     public synchronized void addElement(E obj) {
624         modCount++;
625         ensureCapacityHelper(elementCount + 1);
626         elementData[elementCount++] = obj;
627     }
628 
629     /**
630      * Removes the first (lowest-indexed) occurrence of the argument
631      * from this vector. If the object is found in this vector, each
632      * component in the vector with an index greater or equal to the
633      * object's index is shifted downward to have an index one smaller
634      * than the value it had previously.
635      *
636      * <p>This method is identical in functionality to the
637      * {@link #remove(Object)} method (which is part of the
638      * {@link List} interface).
639      *
640      * @param   obj   the component to be removed
641      * @return  {@code true} if the argument was a component of this
642      *          vector; {@code false} otherwise.
643      */
removeElement(Object obj)644     public synchronized boolean removeElement(Object obj) {
645         modCount++;
646         int i = indexOf(obj);
647         if (i >= 0) {
648             removeElementAt(i);
649             return true;
650         }
651         return false;
652     }
653 
654     /**
655      * Removes all components from this vector and sets its size to zero.
656      *
657      * <p>This method is identical in functionality to the {@link #clear}
658      * method (which is part of the {@link List} interface).
659      */
removeAllElements()660     public synchronized void removeAllElements() {
661         modCount++;
662         // Let gc do its work
663         for (int i = 0; i < elementCount; i++)
664             elementData[i] = null;
665 
666         elementCount = 0;
667     }
668 
669     /**
670      * Returns a clone of this vector. The copy will contain a
671      * reference to a clone of the internal data array, not a reference
672      * to the original internal data array of this {@code Vector} object.
673      *
674      * @return  a clone of this vector
675      */
clone()676     public synchronized Object clone() {
677         try {
678             @SuppressWarnings("unchecked")
679                 Vector<E> v = (Vector<E>) super.clone();
680             v.elementData = Arrays.copyOf(elementData, elementCount);
681             v.modCount = 0;
682             return v;
683         } catch (CloneNotSupportedException e) {
684             // this shouldn't happen, since we are Cloneable
685             throw new InternalError(e);
686         }
687     }
688 
689     /**
690      * Returns an array containing all of the elements in this Vector
691      * in the correct order.
692      *
693      * @since 1.2
694      */
toArray()695     public synchronized Object[] toArray() {
696         return Arrays.copyOf(elementData, elementCount);
697     }
698 
699     /**
700      * Returns an array containing all of the elements in this Vector in the
701      * correct order; the runtime type of the returned array is that of the
702      * specified array.  If the Vector fits in the specified array, it is
703      * returned therein.  Otherwise, a new array is allocated with the runtime
704      * type of the specified array and the size of this Vector.
705      *
706      * <p>If the Vector fits in the specified array with room to spare
707      * (i.e., the array has more elements than the Vector),
708      * the element in the array immediately following the end of the
709      * Vector is set to null.  (This is useful in determining the length
710      * of the Vector <em>only</em> if the caller knows that the Vector
711      * does not contain any null elements.)
712      *
713      * @param a the array into which the elements of the Vector are to
714      *          be stored, if it is big enough; otherwise, a new array of the
715      *          same runtime type is allocated for this purpose.
716      * @return an array containing the elements of the Vector
717      * @throws ArrayStoreException if the runtime type of a is not a supertype
718      * of the runtime type of every element in this Vector
719      * @throws NullPointerException if the given array is null
720      * @since 1.2
721      */
722     @SuppressWarnings("unchecked")
toArray(T[] a)723     public synchronized <T> T[] toArray(T[] a) {
724         if (a.length < elementCount)
725             return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
726 
727         System.arraycopy(elementData, 0, a, 0, elementCount);
728 
729         if (a.length > elementCount)
730             a[elementCount] = null;
731 
732         return a;
733     }
734 
735     // Positional Access Operations
736 
737     @SuppressWarnings("unchecked")
elementData(int index)738     E elementData(int index) {
739         return (E) elementData[index];
740     }
741 
742     /**
743      * Returns the element at the specified position in this Vector.
744      *
745      * @param index index of the element to return
746      * @return object at the specified index
747      * @throws ArrayIndexOutOfBoundsException if the index is out of range
748      *            ({@code index < 0 || index >= size()})
749      * @since 1.2
750      */
get(int index)751     public synchronized E get(int index) {
752         if (index >= elementCount)
753             throw new ArrayIndexOutOfBoundsException(index);
754 
755         return elementData(index);
756     }
757 
758     /**
759      * Replaces the element at the specified position in this Vector with the
760      * specified element.
761      *
762      * @param index index of the element to replace
763      * @param element element to be stored at the specified position
764      * @return the element previously at the specified position
765      * @throws ArrayIndexOutOfBoundsException if the index is out of range
766      *         ({@code index < 0 || index >= size()})
767      * @since 1.2
768      */
set(int index, E element)769     public synchronized E set(int index, E element) {
770         if (index >= elementCount)
771             throw new ArrayIndexOutOfBoundsException(index);
772 
773         E oldValue = elementData(index);
774         elementData[index] = element;
775         return oldValue;
776     }
777 
778     /**
779      * Appends the specified element to the end of this Vector.
780      *
781      * @param e element to be appended to this Vector
782      * @return {@code true} (as specified by {@link Collection#add})
783      * @since 1.2
784      */
add(E e)785     public synchronized boolean add(E e) {
786         modCount++;
787         ensureCapacityHelper(elementCount + 1);
788         elementData[elementCount++] = e;
789         return true;
790     }
791 
792     /**
793      * Removes the first occurrence of the specified element in this Vector
794      * If the Vector does not contain the element, it is unchanged.  More
795      * formally, removes the element with the lowest index i such that
796      * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
797      * an element exists).
798      *
799      * @param o element to be removed from this Vector, if present
800      * @return true if the Vector contained the specified element
801      * @since 1.2
802      */
remove(Object o)803     public boolean remove(Object o) {
804         return removeElement(o);
805     }
806 
807     /**
808      * Inserts the specified element at the specified position in this Vector.
809      * Shifts the element currently at that position (if any) and any
810      * subsequent elements to the right (adds one to their indices).
811      *
812      * @param index index at which the specified element is to be inserted
813      * @param element element to be inserted
814      * @throws ArrayIndexOutOfBoundsException if the index is out of range
815      *         ({@code index < 0 || index > size()})
816      * @since 1.2
817      */
add(int index, E element)818     public void add(int index, E element) {
819         insertElementAt(element, index);
820     }
821 
822     /**
823      * Removes the element at the specified position in this Vector.
824      * Shifts any subsequent elements to the left (subtracts one from their
825      * indices).  Returns the element that was removed from the Vector.
826      *
827      * @throws ArrayIndexOutOfBoundsException if the index is out of range
828      *         ({@code index < 0 || index >= size()})
829      * @param index the index of the element to be removed
830      * @return element that was removed
831      * @since 1.2
832      */
remove(int index)833     public synchronized E remove(int index) {
834         modCount++;
835         if (index >= elementCount)
836             throw new ArrayIndexOutOfBoundsException(index);
837         E oldValue = elementData(index);
838 
839         int numMoved = elementCount - index - 1;
840         if (numMoved > 0)
841             System.arraycopy(elementData, index+1, elementData, index,
842                              numMoved);
843         elementData[--elementCount] = null; // Let gc do its work
844 
845         return oldValue;
846     }
847 
848     /**
849      * Removes all of the elements from this Vector.  The Vector will
850      * be empty after this call returns (unless it throws an exception).
851      *
852      * @since 1.2
853      */
clear()854     public void clear() {
855         removeAllElements();
856     }
857 
858     // Bulk Operations
859 
860     /**
861      * Returns true if this Vector contains all of the elements in the
862      * specified Collection.
863      *
864      * @param   c a collection whose elements will be tested for containment
865      *          in this Vector
866      * @return true if this Vector contains all of the elements in the
867      *         specified collection
868      * @throws NullPointerException if the specified collection is null
869      */
containsAll(Collection<?> c)870     public synchronized boolean containsAll(Collection<?> c) {
871         return super.containsAll(c);
872     }
873 
874     /**
875      * Appends all of the elements in the specified Collection to the end of
876      * this Vector, in the order that they are returned by the specified
877      * Collection's Iterator.  The behavior of this operation is undefined if
878      * the specified Collection is modified while the operation is in progress.
879      * (This implies that the behavior of this call is undefined if the
880      * specified Collection is this Vector, and this Vector is nonempty.)
881      *
882      * @param c elements to be inserted into this Vector
883      * @return {@code true} if this Vector changed as a result of the call
884      * @throws NullPointerException if the specified collection is null
885      * @since 1.2
886      */
addAll(Collection<? extends E> c)887     public synchronized boolean addAll(Collection<? extends E> c) {
888         modCount++;
889         Object[] a = c.toArray();
890         int numNew = a.length;
891         ensureCapacityHelper(elementCount + numNew);
892         System.arraycopy(a, 0, elementData, elementCount, numNew);
893         elementCount += numNew;
894         return numNew != 0;
895     }
896 
897     /**
898      * Removes from this Vector all of its elements that are contained in the
899      * specified Collection.
900      *
901      * @param c a collection of elements to be removed from the Vector
902      * @return true if this Vector changed as a result of the call
903      * @throws ClassCastException if the types of one or more elements
904      *         in this vector are incompatible with the specified
905      *         collection
906      * (<a href="Collection.html#optional-restrictions">optional</a>)
907      * @throws NullPointerException if this vector contains one or more null
908      *         elements and the specified collection does not support null
909      *         elements
910      * (<a href="Collection.html#optional-restrictions">optional</a>),
911      *         or if the specified collection is null
912      * @since 1.2
913      */
removeAll(Collection<?> c)914     public synchronized boolean removeAll(Collection<?> c) {
915         return super.removeAll(c);
916     }
917 
918     /**
919      * Retains only the elements in this Vector that are contained in the
920      * specified Collection.  In other words, removes from this Vector all
921      * of its elements that are not contained in the specified Collection.
922      *
923      * @param c a collection of elements to be retained in this Vector
924      *          (all other elements are removed)
925      * @return true if this Vector changed as a result of the call
926      * @throws ClassCastException if the types of one or more elements
927      *         in this vector are incompatible with the specified
928      *         collection
929      * (<a href="Collection.html#optional-restrictions">optional</a>)
930      * @throws NullPointerException if this vector contains one or more null
931      *         elements and the specified collection does not support null
932      *         elements
933      *         (<a href="Collection.html#optional-restrictions">optional</a>),
934      *         or if the specified collection is null
935      * @since 1.2
936      */
retainAll(Collection<?> c)937     public synchronized boolean retainAll(Collection<?> c) {
938         return super.retainAll(c);
939     }
940 
941     /**
942      * Inserts all of the elements in the specified Collection into this
943      * Vector at the specified position.  Shifts the element currently at
944      * that position (if any) and any subsequent elements to the right
945      * (increases their indices).  The new elements will appear in the Vector
946      * in the order that they are returned by the specified Collection's
947      * iterator.
948      *
949      * @param index index at which to insert the first element from the
950      *              specified collection
951      * @param c elements to be inserted into this Vector
952      * @return {@code true} if this Vector changed as a result of the call
953      * @throws ArrayIndexOutOfBoundsException if the index is out of range
954      *         ({@code index < 0 || index > size()})
955      * @throws NullPointerException if the specified collection is null
956      * @since 1.2
957      */
addAll(int index, Collection<? extends E> c)958     public synchronized boolean addAll(int index, Collection<? extends E> c) {
959         modCount++;
960         if (index < 0 || index > elementCount)
961             throw new ArrayIndexOutOfBoundsException(index);
962 
963         Object[] a = c.toArray();
964         int numNew = a.length;
965         ensureCapacityHelper(elementCount + numNew);
966 
967         int numMoved = elementCount - index;
968         if (numMoved > 0)
969             System.arraycopy(elementData, index, elementData, index + numNew,
970                              numMoved);
971 
972         System.arraycopy(a, 0, elementData, index, numNew);
973         elementCount += numNew;
974         return numNew != 0;
975     }
976 
977     /**
978      * Compares the specified Object with this Vector for equality.  Returns
979      * true if and only if the specified Object is also a List, both Lists
980      * have the same size, and all corresponding pairs of elements in the two
981      * Lists are <em>equal</em>.  (Two elements {@code e1} and
982      * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
983      * e1.equals(e2))}.)  In other words, two Lists are defined to be
984      * equal if they contain the same elements in the same order.
985      *
986      * @param o the Object to be compared for equality with this Vector
987      * @return true if the specified Object is equal to this Vector
988      */
equals(Object o)989     public synchronized boolean equals(Object o) {
990         return super.equals(o);
991     }
992 
993     /**
994      * Returns the hash code value for this Vector.
995      */
hashCode()996     public synchronized int hashCode() {
997         return super.hashCode();
998     }
999 
1000     /**
1001      * Returns a string representation of this Vector, containing
1002      * the String representation of each element.
1003      */
toString()1004     public synchronized String toString() {
1005         return super.toString();
1006     }
1007 
1008     /**
1009      * Returns a view of the portion of this List between fromIndex,
1010      * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1011      * equal, the returned List is empty.)  The returned List is backed by this
1012      * List, so changes in the returned List are reflected in this List, and
1013      * vice-versa.  The returned List supports all of the optional List
1014      * operations supported by this List.
1015      *
1016      * <p>This method eliminates the need for explicit range operations (of
1017      * the sort that commonly exist for arrays).  Any operation that expects
1018      * a List can be used as a range operation by operating on a subList view
1019      * instead of a whole List.  For example, the following idiom
1020      * removes a range of elements from a List:
1021      * <pre>
1022      *      list.subList(from, to).clear();
1023      * </pre>
1024      * Similar idioms may be constructed for indexOf and lastIndexOf,
1025      * and all of the algorithms in the Collections class can be applied to
1026      * a subList.
1027      *
1028      * <p>The semantics of the List returned by this method become undefined if
1029      * the backing list (i.e., this List) is <i>structurally modified</i> in
1030      * any way other than via the returned List.  (Structural modifications are
1031      * those that change the size of the List, or otherwise perturb it in such
1032      * a fashion that iterations in progress may yield incorrect results.)
1033      *
1034      * @param fromIndex low endpoint (inclusive) of the subList
1035      * @param toIndex high endpoint (exclusive) of the subList
1036      * @return a view of the specified range within this List
1037      * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1038      *         {@code (fromIndex < 0 || toIndex > size)}
1039      * @throws IllegalArgumentException if the endpoint indices are out of order
1040      *         {@code (fromIndex > toIndex)}
1041      */
subList(int fromIndex, int toIndex)1042     public synchronized List<E> subList(int fromIndex, int toIndex) {
1043         return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1044                                             this);
1045     }
1046 
1047     /**
1048      * Removes from this list all of the elements whose index is between
1049      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1050      * Shifts any succeeding elements to the left (reduces their index).
1051      * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1052      * (If {@code toIndex==fromIndex}, this operation has no effect.)
1053      */
removeRange(int fromIndex, int toIndex)1054     protected synchronized void removeRange(int fromIndex, int toIndex) {
1055         modCount++;
1056         int numMoved = elementCount - toIndex;
1057         System.arraycopy(elementData, toIndex, elementData, fromIndex,
1058                          numMoved);
1059 
1060         // Let gc do its work
1061         int newElementCount = elementCount - (toIndex-fromIndex);
1062         while (elementCount != newElementCount)
1063             elementData[--elementCount] = null;
1064     }
1065 
1066     /**
1067      * Loads a {@code Vector} instance from a stream
1068      * (that is, deserializes it).
1069      * This method performs checks to ensure the consistency
1070      * of the fields.
1071      *
1072      * @param in the stream
1073      * @throws java.io.IOException if an I/O error occurs
1074      * @throws ClassNotFoundException if the stream contains data
1075      *         of a non-existing class
1076      */
readObject(ObjectInputStream in)1077     private void readObject(ObjectInputStream in)
1078             throws IOException, ClassNotFoundException {
1079         ObjectInputStream.GetField gfields = in.readFields();
1080         int count = gfields.get("elementCount", 0);
1081         Object[] data = (Object[])gfields.get("elementData", null);
1082         if (count < 0 || data == null || count > data.length) {
1083             throw new StreamCorruptedException("Inconsistent vector internals");
1084         }
1085         elementCount = count;
1086         elementData = data.clone();
1087     }
1088 
1089     /**
1090      * Save the state of the {@code Vector} instance to a stream (that
1091      * is, serialize it).
1092      * This method performs synchronization to ensure the consistency
1093      * of the serialized data.
1094      */
writeObject(java.io.ObjectOutputStream s)1095     private void writeObject(java.io.ObjectOutputStream s)
1096             throws java.io.IOException {
1097         final java.io.ObjectOutputStream.PutField fields = s.putFields();
1098         final Object[] data;
1099         synchronized (this) {
1100             fields.put("capacityIncrement", capacityIncrement);
1101             fields.put("elementCount", elementCount);
1102             data = elementData.clone();
1103         }
1104         fields.put("elementData", data);
1105         s.writeFields();
1106     }
1107 
1108     /**
1109      * Returns a list iterator over the elements in this list (in proper
1110      * sequence), starting at the specified position in the list.
1111      * The specified index indicates the first element that would be
1112      * returned by an initial call to {@link ListIterator#next next}.
1113      * An initial call to {@link ListIterator#previous previous} would
1114      * return the element with the specified index minus one.
1115      *
1116      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1117      *
1118      * @throws IndexOutOfBoundsException {@inheritDoc}
1119      */
listIterator(int index)1120     public synchronized ListIterator<E> listIterator(int index) {
1121         if (index < 0 || index > elementCount)
1122             throw new IndexOutOfBoundsException("Index: "+index);
1123         return new ListItr(index);
1124     }
1125 
1126     /**
1127      * Returns a list iterator over the elements in this list (in proper
1128      * sequence).
1129      *
1130      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1131      *
1132      * @see #listIterator(int)
1133      */
listIterator()1134     public synchronized ListIterator<E> listIterator() {
1135         return new ListItr(0);
1136     }
1137 
1138     /**
1139      * Returns an iterator over the elements in this list in proper sequence.
1140      *
1141      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1142      *
1143      * @return an iterator over the elements in this list in proper sequence
1144      */
iterator()1145     public synchronized Iterator<E> iterator() {
1146         return new Itr();
1147     }
1148 
1149     /**
1150      * An optimized version of AbstractList.Itr
1151      */
1152     private class Itr implements Iterator<E> {
1153         int cursor;       // index of next element to return
1154         int lastRet = -1; // index of last element returned; -1 if no such
1155         int expectedModCount = modCount;
1156 
hasNext()1157         public boolean hasNext() {
1158             // Racy but within spec, since modifications are checked
1159             // within or after synchronization in next/previous
1160             return cursor != elementCount;
1161         }
1162 
next()1163         public E next() {
1164             synchronized (Vector.this) {
1165                 checkForComodification();
1166                 int i = cursor;
1167                 if (i >= elementCount)
1168                     throw new NoSuchElementException();
1169                 cursor = i + 1;
1170                 return elementData(lastRet = i);
1171             }
1172         }
1173 
remove()1174         public void remove() {
1175             if (lastRet == -1)
1176                 throw new IllegalStateException();
1177             synchronized (Vector.this) {
1178                 checkForComodification();
1179                 Vector.this.remove(lastRet);
1180                 expectedModCount = modCount;
1181             }
1182             cursor = lastRet;
1183             lastRet = -1;
1184         }
1185 
1186         @Override
forEachRemaining(Consumer<? super E> action)1187         public void forEachRemaining(Consumer<? super E> action) {
1188             Objects.requireNonNull(action);
1189             synchronized (Vector.this) {
1190                 final int size = elementCount;
1191                 int i = cursor;
1192                 if (i >= size) {
1193                     return;
1194                 }
1195         @SuppressWarnings("unchecked")
1196                 final E[] elementData = (E[]) Vector.this.elementData;
1197                 if (i >= elementData.length) {
1198                     throw new ConcurrentModificationException();
1199                 }
1200                 while (i != size && modCount == expectedModCount) {
1201                     action.accept(elementData[i++]);
1202                 }
1203                 // update once at end of iteration to reduce heap write traffic
1204                 cursor = i;
1205                 lastRet = i - 1;
1206                 checkForComodification();
1207             }
1208         }
1209 
checkForComodification()1210         final void checkForComodification() {
1211             if (modCount != expectedModCount)
1212                 throw new ConcurrentModificationException();
1213         }
1214     }
1215 
1216     /**
1217      * An optimized version of AbstractList.ListItr
1218      */
1219     final class ListItr extends Itr implements ListIterator<E> {
ListItr(int index)1220         ListItr(int index) {
1221             super();
1222             cursor = index;
1223         }
1224 
hasPrevious()1225         public boolean hasPrevious() {
1226             return cursor != 0;
1227         }
1228 
nextIndex()1229         public int nextIndex() {
1230             return cursor;
1231         }
1232 
previousIndex()1233         public int previousIndex() {
1234             return cursor - 1;
1235         }
1236 
previous()1237         public E previous() {
1238             synchronized (Vector.this) {
1239                 checkForComodification();
1240                 int i = cursor - 1;
1241                 if (i < 0)
1242                     throw new NoSuchElementException();
1243                 cursor = i;
1244                 return elementData(lastRet = i);
1245             }
1246         }
1247 
set(E e)1248         public void set(E e) {
1249             if (lastRet == -1)
1250                 throw new IllegalStateException();
1251             synchronized (Vector.this) {
1252                 checkForComodification();
1253                 Vector.this.set(lastRet, e);
1254             }
1255         }
1256 
add(E e)1257         public void add(E e) {
1258             int i = cursor;
1259             synchronized (Vector.this) {
1260                 checkForComodification();
1261                 Vector.this.add(i, e);
1262                 expectedModCount = modCount;
1263             }
1264             cursor = i + 1;
1265             lastRet = -1;
1266         }
1267     }
1268 
1269     @Override
forEach(Consumer<? super E> action)1270     public synchronized void forEach(Consumer<? super E> action) {
1271         Objects.requireNonNull(action);
1272         final int expectedModCount = modCount;
1273         @SuppressWarnings("unchecked")
1274         final E[] elementData = (E[]) this.elementData;
1275         final int elementCount = this.elementCount;
1276         for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1277             action.accept(elementData[i]);
1278         }
1279         if (modCount != expectedModCount) {
1280             throw new ConcurrentModificationException();
1281         }
1282     }
1283 
1284     @Override
1285     @SuppressWarnings("unchecked")
removeIf(Predicate<? super E> filter)1286     public synchronized boolean removeIf(Predicate<? super E> filter) {
1287         Objects.requireNonNull(filter);
1288         // figure out which elements are to be removed
1289         // any exception thrown from the filter predicate at this stage
1290         // will leave the collection unmodified
1291         int removeCount = 0;
1292         final int size = elementCount;
1293         final BitSet removeSet = new BitSet(size);
1294         final int expectedModCount = modCount;
1295         for (int i=0; modCount == expectedModCount && i < size; i++) {
1296             @SuppressWarnings("unchecked")
1297             final E element = (E) elementData[i];
1298             if (filter.test(element)) {
1299                 removeSet.set(i);
1300                 removeCount++;
1301             }
1302         }
1303         if (modCount != expectedModCount) {
1304             throw new ConcurrentModificationException();
1305         }
1306 
1307         // shift surviving elements left over the spaces left by removed elements
1308         final boolean anyToRemove = removeCount > 0;
1309         if (anyToRemove) {
1310             final int newSize = size - removeCount;
1311             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1312                 i = removeSet.nextClearBit(i);
1313                 elementData[j] = elementData[i];
1314             }
1315             for (int k=newSize; k < size; k++) {
1316                 elementData[k] = null;  // Let gc do its work
1317             }
1318             elementCount = newSize;
1319             if (modCount != expectedModCount) {
1320                 throw new ConcurrentModificationException();
1321             }
1322             modCount++;
1323         }
1324 
1325         return anyToRemove;
1326     }
1327 
1328     @Override
1329     @SuppressWarnings("unchecked")
replaceAll(UnaryOperator<E> operator)1330     public synchronized void replaceAll(UnaryOperator<E> operator) {
1331         Objects.requireNonNull(operator);
1332         final int expectedModCount = modCount;
1333         final int size = elementCount;
1334         for (int i=0; modCount == expectedModCount && i < size; i++) {
1335             elementData[i] = operator.apply((E) elementData[i]);
1336         }
1337         if (modCount != expectedModCount) {
1338             throw new ConcurrentModificationException();
1339         }
1340         modCount++;
1341     }
1342 
1343     @SuppressWarnings("unchecked")
1344     @Override
sort(Comparator<? super E> c)1345     public synchronized void sort(Comparator<? super E> c) {
1346         final int expectedModCount = modCount;
1347         Arrays.sort((E[]) elementData, 0, elementCount, c);
1348         if (modCount != expectedModCount) {
1349             throw new ConcurrentModificationException();
1350         }
1351         modCount++;
1352     }
1353 
1354     /**
1355      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1356      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1357      * list.
1358      *
1359      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1360      * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1361      * Overriding implementations should document the reporting of additional
1362      * characteristic values.
1363      *
1364      * @return a {@code Spliterator} over the elements in this list
1365      * @since 1.8
1366      */
1367     @Override
spliterator()1368     public Spliterator<E> spliterator() {
1369         return new VectorSpliterator<>(this, null, 0, -1, 0);
1370     }
1371 
1372     /** Similar to ArrayList Spliterator */
1373     static final class VectorSpliterator<E> implements Spliterator<E> {
1374         private final Vector<E> list;
1375         private Object[] array;
1376         private int index; // current index, modified on advance/split
1377         private int fence; // -1 until used; then one past last index
1378         private int expectedModCount; // initialized when fence set
1379 
1380         /** Create new spliterator covering the given  range */
VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence, int expectedModCount)1381         VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1382                           int expectedModCount) {
1383             this.list = list;
1384             this.array = array;
1385             this.index = origin;
1386             this.fence = fence;
1387             this.expectedModCount = expectedModCount;
1388         }
1389 
getFence()1390         private int getFence() { // initialize on first use
1391             int hi;
1392             if ((hi = fence) < 0) {
1393                 synchronized(list) {
1394                     array = list.elementData;
1395                     expectedModCount = list.modCount;
1396                     hi = fence = list.elementCount;
1397                 }
1398             }
1399             return hi;
1400         }
1401 
trySplit()1402         public Spliterator<E> trySplit() {
1403             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1404             return (lo >= mid) ? null :
1405                 new VectorSpliterator<E>(list, array, lo, index = mid,
1406                                          expectedModCount);
1407         }
1408 
1409         @SuppressWarnings("unchecked")
tryAdvance(Consumer<? super E> action)1410         public boolean tryAdvance(Consumer<? super E> action) {
1411             int i;
1412             if (action == null)
1413                 throw new NullPointerException();
1414             if (getFence() > (i = index)) {
1415                 index = i + 1;
1416                 action.accept((E)array[i]);
1417                 if (list.modCount != expectedModCount)
1418                     throw new ConcurrentModificationException();
1419                 return true;
1420             }
1421             return false;
1422         }
1423 
1424         @SuppressWarnings("unchecked")
forEachRemaining(Consumer<? super E> action)1425         public void forEachRemaining(Consumer<? super E> action) {
1426             int i, hi; // hoist accesses and checks from loop
1427             Vector<E> lst; Object[] a;
1428             if (action == null)
1429                 throw new NullPointerException();
1430             if ((lst = list) != null) {
1431                 if ((hi = fence) < 0) {
1432                     synchronized(lst) {
1433                         expectedModCount = lst.modCount;
1434                         a = array = lst.elementData;
1435                         hi = fence = lst.elementCount;
1436                     }
1437                 }
1438                 else
1439                     a = array;
1440                 if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1441                     while (i < hi)
1442                         action.accept((E) a[i++]);
1443                     if (lst.modCount == expectedModCount)
1444                         return;
1445                 }
1446             }
1447             throw new ConcurrentModificationException();
1448         }
1449 
estimateSize()1450         public long estimateSize() {
1451             return (long) (getFence() - index);
1452         }
1453 
characteristics()1454         public int characteristics() {
1455             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1456         }
1457     }
1458 }
1459