ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
Revision: 1.58
Committed: Fri Jul 24 20:57:26 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.57: +7 -6 lines
Log Message:
8231800: Better listing of arrays

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