ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
Revision: 1.38
Committed: Thu Dec 1 00:35:21 2016 UTC (7 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.37: +7 -18 lines
Log Message:
cleaner and faster VectorSpliterator.forEachRemaining

File Contents

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