ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
Revision: 1.48
Committed: Wed Mar 28 02:50:41 2018 UTC (6 years, 1 month ago) by jsr166
Branch: MAIN
Changes since 1.47: +1 -1 lines
Log Message:
sync Oracle copyright years

File Contents

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