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