ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
Revision: 1.56
Committed: Fri Aug 30 18:05:39 2019 UTC (4 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.55: +3 -0 lines
Log Message:
accommodate 8229997: Apply java.io.Serial annotations in java.base

File Contents

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