ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
(Generate patch)

Comparing jsr166/src/main/java/util/Vector.java (file contents):
Revision 1.13 by jsr166, Sun May 28 23:36:29 2006 UTC vs.
Revision 1.46 by jsr166, Sat May 6 06:49:46 2017 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Oracle designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Oracle in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
27  
28 + import java.util.function.Consumer;
29 + import java.util.function.Predicate;
30 + import java.util.function.UnaryOperator;
31 +
32   /**
33 < * The <code>Vector</code> class implements a growable array of
33 > * The {@code Vector} class implements a growable array of
34   * objects. Like an array, it contains components that can be
35   * accessed using an integer index. However, the size of a
36 < * <code>Vector</code> can grow or shrink as needed to accommodate
37 < * adding and removing items after the <code>Vector</code> has been created.
36 > * {@code Vector} can grow or shrink as needed to accommodate
37 > * adding and removing items after the {@code Vector} has been created.
38   *
39   * <p>Each vector tries to optimize storage management by maintaining a
40 < * <code>capacity</code> and a <code>capacityIncrement</code>. The
41 < * <code>capacity</code> is always at least as large as the vector
40 > * {@code capacity} and a {@code capacityIncrement}. The
41 > * {@code capacity} is always at least as large as the vector
42   * 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 < * <code>capacityIncrement</code>. An application can increase the
44 > * {@code capacityIncrement}. An application can increase the
45   * capacity of a vector before inserting a large number of
46   * components; this reduces the amount of incremental reallocation.
47   *
48 < * <p>The Iterators returned by Vector's iterator and listIterator
49 < * methods are <em>fail-fast</em>: if the Vector is structurally modified
50 < * at any time after the Iterator is created, in any way except through the
51 < * Iterator's own remove or add methods, the Iterator will throw a
52 < * ConcurrentModificationException.  Thus, in the face of concurrent
53 < * modification, the Iterator fails quickly and cleanly, rather than risking
54 < * arbitrary, non-deterministic behavior at an undetermined time in the future.
55 < * The Enumerations returned by Vector's elements method are <em>not</em>
56 < * fail-fast.
48 > * <p id="fail-fast">
49 > * 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 > * 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   *
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 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
66 > * throw {@code ConcurrentModificationException} on a best-effort basis.
67   * 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   * should be used only to detect bugs.</i>
70   *
71   * <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 < * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
74 < * Collections Framework</a>.  Unlike the new collection
75 < * implementations, {@code Vector} is synchronized.
73 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
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 > *
79 > * @param <E> Type of component elements
80   *
81   * @author  Lee Boynton
82   * @author  Jonathan Payne
52 * @version %I%, %G%
83   * @see Collection
54 * @see List
55 * @see ArrayList
84   * @see LinkedList
85 < * @since   JDK1.0
85 > * @since   1.0
86   */
87   public class Vector<E>
88      extends AbstractList<E>
# Line 63 | Line 91 | public class Vector<E>
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 <     * and is at least large enough to contain all the vector's elements.<p>
94 >     * and is at least large enough to contain all the vector's elements.
95       *
96 <     * Any array elements following the last element in the Vector are null.
96 >     * <p>Any array elements following the last element in the Vector are null.
97       *
98       * @serial
99       */
100      protected Object[] elementData;
101  
102      /**
103 <     * The number of valid components in this <tt>Vector</tt> object.
104 <     * Components <tt>elementData[0]</tt> through
105 <     * <tt>elementData[elementCount-1]</tt> are the actual items.
103 >     * 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       *
107       * @serial
108       */
# Line 100 | Line 128 | public class Vector<E>
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 <     * @exception IllegalArgumentException if the specified initial capacity
132 <     *               is negative
131 >     * @throws IllegalArgumentException if the specified initial capacity
132 >     *         is negative
133       */
134      public Vector(int initialCapacity, int capacityIncrement) {
135 <        super();
135 >        super();
136          if (initialCapacity < 0)
137              throw new IllegalArgumentException("Illegal Capacity: "+
138                                                 initialCapacity);
139 <        this.elementData = new Object[initialCapacity];
140 <        this.capacityIncrement = capacityIncrement;
139 >        this.elementData = new Object[initialCapacity];
140 >        this.capacityIncrement = capacityIncrement;
141      }
142  
143      /**
# Line 117 | Line 145 | public class Vector<E>
145       * with its capacity increment equal to zero.
146       *
147       * @param   initialCapacity   the initial capacity of the vector
148 <     * @exception IllegalArgumentException if the specified initial capacity
149 <     *               is negative
148 >     * @throws IllegalArgumentException if the specified initial capacity
149 >     *         is negative
150       */
151      public Vector(int initialCapacity) {
152 <        this(initialCapacity, 0);
152 >        this(initialCapacity, 0);
153      }
154  
155      /**
156       * Constructs an empty vector so that its internal data array
157 <     * has size <tt>10</tt> and its standard capacity increment is
157 >     * has size {@code 10} and its standard capacity increment is
158       * zero.
159       */
160      public Vector() {
161 <        this(10);
161 >        this(10);
162      }
163  
164      /**
# Line 144 | Line 172 | public class Vector<E>
172       * @since   1.2
173       */
174      public Vector(Collection<? extends E> c) {
175 <        elementData = c.toArray();
176 <        elementCount = elementData.length;
177 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
178 <        if (elementData.getClass() != Object[].class)
179 <            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
175 >        elementData = c.toArray();
176 >        elementCount = elementData.length;
177 >        // defend against c.toArray (incorrectly) not returning Object[]
178 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
179 >        if (elementData.getClass() != Object[].class)
180 >            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
181      }
182  
183      /**
184       * Copies the components of this vector into the specified array.
185 <     * The item at index <tt>k</tt> in this vector is copied into
186 <     * component <tt>k</tt> of <tt>anArray</tt>.
185 >     * The item at index {@code k} in this vector is copied into
186 >     * component {@code k} of {@code anArray}.
187       *
188       * @param  anArray the array into which the components get copied
189       * @throws NullPointerException if the given array is null
# Line 165 | Line 194 | public class Vector<E>
194       * @see #toArray(Object[])
195       */
196      public synchronized void copyInto(Object[] anArray) {
197 <        System.arraycopy(elementData, 0, anArray, 0, elementCount);
197 >        System.arraycopy(elementData, 0, anArray, 0, elementCount);
198      }
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 <     * its internal data array, kept in the field <tt>elementData</tt>,
204 >     * its internal data array, kept in the field {@code elementData},
205       * 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 <        modCount++;
210 <        int oldCapacity = elementData.length;
211 <        if (elementCount < oldCapacity) {
209 >        modCount++;
210 >        int oldCapacity = elementData.length;
211 >        if (elementCount < oldCapacity) {
212              elementData = Arrays.copyOf(elementData, elementCount);
213 <        }
213 >        }
214      }
215  
216      /**
# Line 190 | Line 219 | public class Vector<E>
219       * the minimum capacity argument.
220       *
221       * <p>If the current capacity of this vector is less than
222 <     * <tt>minCapacity</tt>, then its capacity is increased by replacing its
223 <     * internal data array, kept in the field <tt>elementData</tt>, with a
222 >     * {@code minCapacity}, then its capacity is increased by replacing its
223 >     * internal data array, kept in the field {@code elementData}, with a
224       * larger one.  The size of the new data array will be the old size plus
225 <     * <tt>capacityIncrement</tt>, unless the value of
226 <     * <tt>capacityIncrement</tt> is less than or equal to zero, in which case
225 >     * {@code capacityIncrement}, unless the value of
226 >     * {@code capacityIncrement} is less than or equal to zero, in which case
227       * the new capacity will be twice the old capacity; but if this new size
228 <     * is still smaller than <tt>minCapacity</tt>, then the new capacity will
229 <     * be <tt>minCapacity</tt>.
228 >     * is still smaller than {@code minCapacity}, then the new capacity will
229 >     * be {@code minCapacity}.
230       *
231       * @param minCapacity the desired minimum capacity
232       */
233      public synchronized void ensureCapacity(int minCapacity) {
234 <        modCount++;
235 <        ensureCapacityHelper(minCapacity);
234 >        if (minCapacity > 0) {
235 >            modCount++;
236 >            if (minCapacity > elementData.length)
237 >                grow(minCapacity);
238 >        }
239      }
240  
241      /**
242 <     * This implements the unsynchronized semantics of ensureCapacity.
243 <     * Synchronized methods in this class can internally call this
244 <     * method for ensuring capacity without incurring the cost of an
245 <     * extra synchronization.
246 <     *
247 <     * @see java.util.Vector#ensureCapacity(int)
248 <     */
249 <    private void ensureCapacityHelper(int minCapacity) {
250 <        int oldCapacity = elementData.length;
251 <        if (minCapacity > oldCapacity) {
252 <            Object[] oldData = elementData;
253 <            int newCapacity = (capacityIncrement > 0) ?
254 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
255 <            if (newCapacity < minCapacity) {
256 <                newCapacity = minCapacity;
257 <            }
258 <            elementData = Arrays.copyOf(elementData, newCapacity);
259 <        }
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 >    }
264 >
265 >    /**
266 >     * 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 >     *
270 >     * @param minCapacity the desired minimum capacity
271 >     * @throws OutOfMemoryError if minCapacity is less than zero
272 >     */
273 >    private int newCapacity(int minCapacity) {
274 >        // overflow-conscious code
275 >        int oldCapacity = elementData.length;
276 >        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      }
295  
296      /**
297       * Sets the size of this vector. If the new size is greater than the
298 <     * current size, new <code>null</code> items are added to the end of
298 >     * current size, new {@code null} items are added to the end of
299       * the vector. If the new size is less than the current size, all
300 <     * components at index <code>newSize</code> and greater are discarded.
300 >     * components at index {@code newSize} and greater are discarded.
301       *
302 <     * @param   newSize   the new size of this vector
303 <     * @throws  ArrayIndexOutOfBoundsException if new size is negative
302 >     * @param  newSize   the new size of this vector
303 >     * @throws ArrayIndexOutOfBoundsException if the new size is negative
304       */
305      public synchronized void setSize(int newSize) {
306 <        modCount++;
307 <        if (newSize > elementCount) {
308 <            ensureCapacityHelper(newSize);
309 <        } else {
310 <            for (int i = newSize ; i < elementCount ; i++) {
311 <                elementData[i] = null;
312 <            }
247 <        }
248 <        elementCount = newSize;
306 >        modCount++;
307 >        if (newSize > elementData.length)
308 >            grow(newSize);
309 >        final Object[] es = elementData;
310 >        for (int to = elementCount, i = newSize; i < to; i++)
311 >            es[i] = null;
312 >        elementCount = newSize;
313      }
314  
315      /**
316       * Returns the current capacity of this vector.
317       *
318       * @return  the current capacity (the length of its internal
319 <     *          data array, kept in the field <tt>elementData</tt>
319 >     *          data array, kept in the field {@code elementData}
320       *          of this vector)
321       */
322      public synchronized int capacity() {
323 <        return elementData.length;
323 >        return elementData.length;
324      }
325  
326      /**
# Line 265 | Line 329 | public class Vector<E>
329       * @return  the number of components in this vector
330       */
331      public synchronized int size() {
332 <        return elementCount;
332 >        return elementCount;
333      }
334  
335      /**
336       * Tests if this vector has no components.
337       *
338 <     * @return  <code>true</code> if and only if this vector has
338 >     * @return  {@code true} if and only if this vector has
339       *          no components, that is, its size is zero;
340 <     *          <code>false</code> otherwise.
340 >     *          {@code false} otherwise.
341       */
342      public synchronized boolean isEmpty() {
343 <        return elementCount == 0;
343 >        return elementCount == 0;
344      }
345  
346      /**
347       * Returns an enumeration of the components of this vector. The
348 <     * returned <tt>Enumeration</tt> object will generate all items in
349 <     * this vector. The first item generated is the item at index <tt>0</tt>,
350 <     * then the item at index <tt>1</tt>, and so on.
348 >     * returned {@code Enumeration} object will generate all items in
349 >     * this vector. The first item generated is the item at index {@code 0},
350 >     * 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       *
354       * @return  an enumeration of the components of this vector
289     * @see     Enumeration
355       * @see     Iterator
356       */
357      public Enumeration<E> elements() {
358 <        return new Enumeration<E>() {
359 <            int count = 0;
358 >        return new Enumeration<E>() {
359 >            int count = 0;
360  
361 <            public boolean hasMoreElements() {
362 <                return count < elementCount;
363 <            }
364 <
365 <            public E nextElement() {
366 <                synchronized (Vector.this) {
367 <                    if (count < elementCount) {
368 <                        return (E)elementData[count++];
369 <                    }
370 <                }
371 <                throw new NoSuchElementException("Vector Enumeration");
372 <            }
373 <        };
361 >            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      }
375  
376      /**
377 <     * Returns <tt>true</tt> if this vector contains the specified element.
378 <     * More formally, returns <tt>true</tt> if and only if this vector
379 <     * contains at least one element <tt>e</tt> such that
380 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
377 >     * 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 >     * {@code Objects.equals(o, e)}.
381       *
382       * @param o element whose presence in this vector is to be tested
383 <     * @return <tt>true</tt> if this vector contains the specified element
383 >     * @return {@code true} if this vector contains the specified element
384       */
385      public boolean contains(Object o) {
386 <        return indexOf(o, 0) >= 0;
386 >        return indexOf(o, 0) >= 0;
387      }
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 <     * More formally, returns the lowest index <tt>i</tt> such that
393 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
392 >     * More formally, returns the lowest index {@code i} such that
393 >     * {@code Objects.equals(o, get(i))},
394       * or -1 if there is no such index.
395       *
396       * @param o element to search for
# Line 333 | Line 398 | public class Vector<E>
398       *         this vector, or -1 if this vector does not contain the element
399       */
400      public int indexOf(Object o) {
401 <        return indexOf(o, 0);
401 >        return indexOf(o, 0);
402      }
403  
404      /**
405       * Returns the index of the first occurrence of the specified element in
406 <     * this vector, searching forwards from <tt>index</tt>, or returns -1 if
406 >     * this vector, searching forwards from {@code index}, or returns -1 if
407       * the element is not found.
408 <     * More formally, returns the lowest index <tt>i</tt> such that
409 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
408 >     * More formally, returns the lowest index {@code i} such that
409 >     * {@code (i >= index && Objects.equals(o, get(i)))},
410       * 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 <     *         this vector at position <tt>index</tt> or later in the vector;
416 <     *         <tt>-1</tt> if the element is not found.
415 >     *         this vector at position {@code index} or later in the vector;
416 >     *         {@code -1} if the element is not found.
417       * @throws IndexOutOfBoundsException if the specified index is negative
418       * @see     Object#equals(Object)
419       */
420      public synchronized int indexOf(Object o, int index) {
421 <        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;
421 >        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      }
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 <     * More formally, returns the highest index <tt>i</tt> such that
437 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
436 >     * More formally, returns the highest index {@code i} such that
437 >     * {@code Objects.equals(o, get(i))},
438       * or -1 if there is no such index.
439       *
440       * @param o element to search for
# Line 377 | Line 442 | public class Vector<E>
442       *         this vector, or -1 if this vector does not contain the element
443       */
444      public synchronized int lastIndexOf(Object o) {
445 <        return lastIndexOf(o, elementCount-1);
445 >        return lastIndexOf(o, elementCount-1);
446      }
447  
448      /**
449       * Returns the index of the last occurrence of the specified element in
450 <     * this vector, searching backwards from <tt>index</tt>, or returns -1 if
450 >     * this vector, searching backwards from {@code index}, or returns -1 if
451       * the element is not found.
452 <     * More formally, returns the highest index <tt>i</tt> such that
453 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
452 >     * More formally, returns the highest index {@code i} such that
453 >     * {@code (i <= index && Objects.equals(o, get(i)))},
454       * 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 <     *         less than or equal to <tt>index</tt> in this vector;
459 >     *         less than or equal to {@code index} in this vector;
460       *         -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
# Line 400 | Line 465 | public class Vector<E>
465          if (index >= elementCount)
466              throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
467  
468 <        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;
468 >        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      }
479  
480      /**
481 <     * Returns the component at the specified index.<p>
481 >     * Returns the component at the specified index.
482       *
483 <     * This method is identical in functionality to the get method
484 <     * (which is part of the List interface).
483 >     * <p>This method is identical in functionality to the {@link #get(int)}
484 >     * method (which is part of the {@link List} interface).
485       *
486       * @param      index   an index into this vector
487       * @return     the component at the specified index
488 <     * @exception  ArrayIndexOutOfBoundsException  if the <tt>index</tt>
489 <     *             is negative or not less than the current size of this
425 <     *             <tt>Vector</tt> object.
426 <     * @see        #get(int)
427 <     * @see        List
488 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
489 >     *         ({@code index < 0 || index >= size()})
490       */
491      public synchronized E elementAt(int index) {
492 <        if (index >= elementCount) {
493 <            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
494 <        }
492 >        if (index >= elementCount) {
493 >            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
494 >        }
495  
496 <        return (E)elementData[index];
496 >        return elementData(index);
497      }
498  
499      /**
500 <     * Returns the first component (the item at index <tt>0</tt>) of
500 >     * Returns the first component (the item at index {@code 0}) of
501       * this vector.
502       *
503       * @return     the first component of this vector
504 <     * @exception  NoSuchElementException  if this vector has no components
504 >     * @throws NoSuchElementException if this vector has no components
505       */
506      public synchronized E firstElement() {
507 <        if (elementCount == 0) {
508 <            throw new NoSuchElementException();
509 <        }
510 <        return (E)elementData[0];
507 >        if (elementCount == 0) {
508 >            throw new NoSuchElementException();
509 >        }
510 >        return elementData(0);
511      }
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 <     *          <code>size()&nbsp;-&nbsp;1</code>.
518 <     * @exception  NoSuchElementException  if this vector is empty
517 >     *          {@code size() - 1}
518 >     * @throws NoSuchElementException if this vector is empty
519       */
520      public synchronized E lastElement() {
521 <        if (elementCount == 0) {
522 <            throw new NoSuchElementException();
523 <        }
524 <        return (E)elementData[elementCount - 1];
521 >        if (elementCount == 0) {
522 >            throw new NoSuchElementException();
523 >        }
524 >        return elementData(elementCount - 1);
525      }
526  
527      /**
528 <     * Sets the component at the specified <code>index</code> of this
528 >     * Sets the component at the specified {@code index} of this
529       * vector to be the specified object. The previous component at that
530 <     * position is discarded.<p>
530 >     * position is discarded.
531       *
532 <     * The index must be a value greater than or equal to <code>0</code>
533 <     * and less than the current size of the vector. <p>
532 >     * <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       *
535 <     * This method is identical in functionality to the set method
536 <     * (which is part of the List interface). Note that the set method reverses
537 <     * the order of the parameters, to more closely match array usage.  Note
538 <     * also that the set method returns the old value that was stored at the
539 <     * specified position.
535 >     * <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       *
542       * @param      obj     what the component is to be set to
543       * @param      index   the specified index
544 <     * @exception  ArrayIndexOutOfBoundsException  if the index was invalid
545 <     * @see        #size()
483 <     * @see        List
484 <     * @see        #set(int, java.lang.Object)
544 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
545 >     *         ({@code index < 0 || index >= size()})
546       */
547      public synchronized void setElementAt(E obj, int index) {
548 <        if (index >= elementCount) {
549 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
550 <                                                     elementCount);
551 <        }
552 <        elementData[index] = obj;
548 >        if (index >= elementCount) {
549 >            throw new ArrayIndexOutOfBoundsException(index + " >= " +
550 >                                                     elementCount);
551 >        }
552 >        elementData[index] = obj;
553      }
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 <     * <code>index</code> is shifted downward to have an index one
558 >     * {@code index} is shifted downward to have an index one
559       * smaller than the value it had previously. The size of this vector
560 <     * is decreased by <tt>1</tt>.<p>
560 >     * is decreased by {@code 1}.
561       *
562 <     * The index must be a value greater than or equal to <code>0</code>
563 <     * and less than the current size of the vector. <p>
562 >     * <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       *
565 <     * This method is identical in functionality to the remove method
566 <     * (which is part of the List interface).  Note that the remove method
567 <     * returns the old value that was stored at the specified position.
565 >     * <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       *
570       * @param      index   the index of the object to remove
571 <     * @exception  ArrayIndexOutOfBoundsException  if the index was invalid
572 <     * @see        #size()
511 <     * @see        #remove(int)
512 <     * @see        List
571 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
572 >     *         ({@code index < 0 || index >= size()})
573       */
574      public synchronized void removeElementAt(int index) {
575 <        modCount++;
576 <        if (index >= elementCount) {
577 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
578 <                                                     elementCount);
579 <        }
580 <        else if (index < 0) {
581 <            throw new ArrayIndexOutOfBoundsException(index);
582 <        }
583 <        int j = elementCount - index - 1;
584 <        if (j > 0) {
585 <            System.arraycopy(elementData, index + 1, elementData, index, j);
586 <        }
587 <        elementCount--;
588 <        elementData[elementCount] = null; /* to let gc do its work */
575 >        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 >        modCount++;
587 >        elementCount--;
588 >        elementData[elementCount] = null; /* to let gc do its work */
589 >        // checkInvariants();
590      }
591  
592      /**
593       * Inserts the specified object as a component in this vector at the
594 <     * specified <code>index</code>. Each component in this vector with
595 <     * an index greater or equal to the specified <code>index</code> is
594 >     * specified {@code index}. Each component in this vector with
595 >     * an index greater or equal to the specified {@code index} is
596       * shifted upward to have an index one greater than the value it had
597 <     * previously. <p>
597 >     * previously.
598       *
599 <     * The index must be a value greater than or equal to <code>0</code>
599 >     * <p>The index must be a value greater than or equal to {@code 0}
600       * 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 <     * is appended to the Vector.)<p>
602 >     * is appended to the Vector.)
603       *
604 <     * This method is identical in functionality to the add(Object, int) method
605 <     * (which is part of the List interface). Note that the add method reverses
606 <     * the order of the parameters, to more closely match array usage.
604 >     * <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       *
610       * @param      obj     the component to insert
611       * @param      index   where to insert the new component
612 <     * @exception  ArrayIndexOutOfBoundsException  if the index was invalid
613 <     * @see        #size()
551 <     * @see        #add(int, Object)
552 <     * @see        List
612 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
613 >     *         ({@code index < 0 || index > size()})
614       */
615      public synchronized void insertElementAt(E obj, int index) {
616 <        modCount++;
617 <        if (index > elementCount) {
618 <            throw new ArrayIndexOutOfBoundsException(index
619 <                                                     + " > " + elementCount);
620 <        }
621 <        ensureCapacityHelper(elementCount + 1);
622 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
623 <        elementData[index] = obj;
624 <        elementCount++;
616 >        if (index > elementCount) {
617 >            throw new ArrayIndexOutOfBoundsException(index
618 >                                                     + " > " + elementCount);
619 >        }
620 >        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 >        elementData[index] = obj;
629 >        elementCount = s + 1;
630      }
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 <     * increased if its size becomes greater than its capacity. <p>
635 >     * increased if its size becomes greater than its capacity.
636       *
637 <     * This method is identical in functionality to the add(Object) method
638 <     * (which is part of the List interface).
637 >     * <p>This method is identical in functionality to the
638 >     * {@link #add(Object) add(E)}
639 >     * method (which is part of the {@link List} interface).
640       *
641       * @param   obj   the component to be added
575     * @see        #add(Object)
576     * @see        List
642       */
643      public synchronized void addElement(E obj) {
644 <        modCount++;
645 <        ensureCapacityHelper(elementCount + 1);
581 <        elementData[elementCount++] = obj;
644 >        modCount++;
645 >        add(obj, elementData, elementCount);
646      }
647  
648      /**
# Line 586 | Line 650 | public class Vector<E>
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 <     * than the value it had previously.<p>
653 >     * than the value it had previously.
654       *
655 <     * This method is identical in functionality to the remove(Object)
656 <     * method (which is part of the List interface).
655 >     * <p>This method is identical in functionality to the
656 >     * {@link #remove(Object)} method (which is part of the
657 >     * {@link List} interface).
658       *
659       * @param   obj   the component to be removed
660 <     * @return  <code>true</code> if the argument was a component of this
661 <     *          vector; <code>false</code> otherwise.
597 <     * @see     List#remove(Object)
598 <     * @see     List
660 >     * @return  {@code true} if the argument was a component of this
661 >     *          vector; {@code false} otherwise.
662       */
663      public synchronized boolean removeElement(Object obj) {
664 <        modCount++;
665 <        int i = indexOf(obj);
666 <        if (i >= 0) {
667 <            removeElementAt(i);
668 <            return true;
669 <        }
670 <        return false;
664 >        modCount++;
665 >        int i = indexOf(obj);
666 >        if (i >= 0) {
667 >            removeElementAt(i);
668 >            return true;
669 >        }
670 >        return false;
671      }
672  
673      /**
674 <     * Removes all components from this vector and sets its size to zero.<p>
612 <     *
613 <     * This method is identical in functionality to the clear method
614 <     * (which is part of the List interface).
674 >     * Removes all components from this vector and sets its size to zero.
675       *
676 <     * @see     #clear
677 <     * @see     List
676 >     * <p>This method is identical in functionality to the {@link #clear}
677 >     * method (which is part of the {@link List} interface).
678       */
679      public synchronized void removeAllElements() {
680 +        final Object[] es = elementData;
681 +        for (int to = elementCount, i = elementCount = 0; i < to; i++)
682 +            es[i] = null;
683          modCount++;
621        // Let gc do its work
622        for (int i = 0; i < elementCount; i++)
623            elementData[i] = null;
624
625        elementCount = 0;
684      }
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 <     * to the original internal data array of this <tt>Vector</tt> object.
689 >     * to the original internal data array of this {@code Vector} object.
690       *
691       * @return  a clone of this vector
692       */
693      public synchronized Object clone() {
694 <        try {
695 <            Vector<E> v = (Vector<E>) super.clone();
696 <            v.elementData = Arrays.copyOf(elementData, elementCount);
697 <            v.modCount = 0;
698 <            return v;
699 <        } catch (CloneNotSupportedException e) {
700 <            // this shouldn't happen, since we are Cloneable
701 <            throw new InternalError();
702 <        }
694 >        try {
695 >            @SuppressWarnings("unchecked")
696 >            Vector<E> v = (Vector<E>) super.clone();
697 >            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 >            throw new InternalError(e);
703 >        }
704      }
705  
706      /**
# Line 659 | Line 718 | public class Vector<E>
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 <     * type of the specified array and the size of this Vector.<p>
721 >     * type of the specified array and the size of this Vector.
722       *
723 <     * If the Vector fits in the specified array with room to spare
723 >     * <p>If the Vector fits in the specified array with room to spare
724       * (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 +     * @param <T> type of array elements. The same type as {@code <E>} or a
731 +     * supertype of {@code <E>}.
732       * @param a the array into which the elements of the Vector are to
733 <     *          be stored, if it is big enough; otherwise, a new array of the
734 <     *          same runtime type is allocated for this purpose.
733 >     *          be stored, if it is big enough; otherwise, a new array of the
734 >     *          same runtime type is allocated for this purpose.
735       * @return an array containing the elements of the Vector
736 <     * @exception ArrayStoreException the runtime type of a is not a supertype
737 <     * of the runtime type of every element in this Vector
736 >     * @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       * @throws NullPointerException if the given array is null
740       * @since 1.2
741       */
742 +    @SuppressWarnings("unchecked")
743      public synchronized <T> T[] toArray(T[] a) {
744          if (a.length < elementCount)
745              return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
746  
747 <        System.arraycopy(elementData, 0, a, 0, elementCount);
747 >        System.arraycopy(elementData, 0, a, 0, elementCount);
748  
749          if (a.length > elementCount)
750              a[elementCount] = null;
# Line 691 | Line 754 | public class Vector<E>
754  
755      // Positional Access Operations
756  
757 +    @SuppressWarnings("unchecked")
758 +    E elementData(int index) {
759 +        return (E) elementData[index];
760 +    }
761 +
762 +    @SuppressWarnings("unchecked")
763 +    static <E> E elementAt(Object[] es, int index) {
764 +        return (E) es[index];
765 +    }
766 +
767      /**
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 <     * @exception ArrayIndexOutOfBoundsException index is out of range (index
773 <     *            &lt; 0 || index &gt;= size())
772 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
773 >     *            ({@code index < 0 || index >= size()})
774       * @since 1.2
775       */
776      public synchronized E get(int index) {
777 <        if (index >= elementCount)
778 <            throw new ArrayIndexOutOfBoundsException(index);
777 >        if (index >= elementCount)
778 >            throw new ArrayIndexOutOfBoundsException(index);
779  
780 <        return (E)elementData[index];
780 >        return elementData(index);
781      }
782  
783      /**
# Line 714 | Line 787 | public class Vector<E>
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 <     * @exception ArrayIndexOutOfBoundsException index out of range
791 <     *            (index &lt; 0 || index &gt;= size())
790 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
791 >     *         ({@code index < 0 || index >= size()})
792       * @since 1.2
793       */
794      public synchronized E set(int index, E element) {
795 <        if (index >= elementCount)
796 <            throw new ArrayIndexOutOfBoundsException(index);
795 >        if (index >= elementCount)
796 >            throw new ArrayIndexOutOfBoundsException(index);
797  
798 <        Object oldValue = elementData[index];
799 <        elementData[index] = element;
800 <        return (E)oldValue;
798 >        E oldValue = elementData(index);
799 >        elementData[index] = element;
800 >        return oldValue;
801 >    }
802 >
803 >    /**
804 >     * 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 >        // checkInvariants();
814      }
815  
816      /**
817       * Appends the specified element to the end of this Vector.
818       *
819       * @param e element to be appended to this Vector
820 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
820 >     * @return {@code true} (as specified by {@link Collection#add})
821       * @since 1.2
822       */
823      public synchronized boolean add(E e) {
824 <        modCount++;
825 <        ensureCapacityHelper(elementCount + 1);
740 <        elementData[elementCount++] = e;
824 >        modCount++;
825 >        add(e, elementData, elementCount);
826          return true;
827      }
828  
# Line 745 | Line 830 | public class Vector<E>
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 <     * <code>(o==null ? get(i)==null : o.equals(get(i)))</code> (if such
833 >     * {@code Objects.equals(o, get(i))} (if such
834       * an element exists).
835       *
836       * @param o element to be removed from this Vector, if present
# Line 763 | Line 848 | public class Vector<E>
848       *
849       * @param index index at which the specified element is to be inserted
850       * @param element element to be inserted
851 <     * @exception ArrayIndexOutOfBoundsException index is out of range
852 <     *            (index &lt; 0 || index &gt; size())
851 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
852 >     *         ({@code index < 0 || index > size()})
853       * @since 1.2
854       */
855      public void add(int index, E element) {
# Line 776 | Line 861 | public class Vector<E>
861       * Shifts any subsequent elements to the left (subtracts one from their
862       * indices).  Returns the element that was removed from the Vector.
863       *
779     * @exception ArrayIndexOutOfBoundsException index out of range (index
780     *            &lt; 0 || index &gt;= size())
864       * @param index the index of the element to be removed
865       * @return element that was removed
866 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
867 +     *         ({@code index < 0 || index >= size()})
868       * @since 1.2
869       */
870      public synchronized E remove(int index) {
871 <        modCount++;
872 <        if (index >= elementCount)
873 <            throw new ArrayIndexOutOfBoundsException(index);
874 <        Object 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
871 >        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  
882 <        return (E)oldValue;
882 >        // checkInvariants();
883 >        return oldValue;
884      }
885  
886      /**
# Line 816 | Line 902 | public class Vector<E>
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 <     *         specified collection
905 >     *         specified collection
906       * @throws NullPointerException if the specified collection is null
907       */
908      public synchronized boolean containsAll(Collection<?> c) {
# Line 832 | Line 918 | public class Vector<E>
918       * specified Collection is this Vector, and this Vector is nonempty.)
919       *
920       * @param c elements to be inserted into this Vector
921 <     * @return <tt>true</tt> if this Vector changed as a result of the call
921 >     * @return {@code true} if this Vector changed as a result of the call
922       * @throws NullPointerException if the specified collection is null
923       * @since 1.2
924       */
925 <    public synchronized boolean addAll(Collection<? extends E> c) {
840 <        modCount++;
925 >    public boolean addAll(Collection<? extends E> c) {
926          Object[] a = c.toArray();
927 +        modCount++;
928          int numNew = a.length;
929 <        ensureCapacityHelper(elementCount + numNew);
930 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
931 <        elementCount += numNew;
932 <        return numNew != 0;
929 >        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 >            // checkInvariants();
939 >            return true;
940 >        }
941      }
942  
943      /**
# Line 854 | Line 948 | public class Vector<E>
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 <     *         collection (optional)
951 >     *         collection
952 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
953       * @throws NullPointerException if this vector contains one or more null
954       *         elements and the specified collection does not support null
955 <     *         elements (optional), or if the specified collection is null
955 >     *         elements
956 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
957 >     *         or if the specified collection is null
958       * @since 1.2
959       */
960 <    public synchronized boolean removeAll(Collection<?> c) {
961 <        return super.removeAll(c);
960 >    public boolean removeAll(Collection<?> c) {
961 >        Objects.requireNonNull(c);
962 >        return bulkRemove(e -> c.contains(e));
963      }
964  
965      /**
# Line 874 | Line 972 | public class Vector<E>
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 <     *         collection (optional)
975 >     *         collection
976 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
977       * @throws NullPointerException if this vector contains one or more null
978       *         elements and the specified collection does not support null
979 <     *         elements (optional), or if the specified collection is null
979 >     *         elements
980 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
981 >     *         or if the specified collection is null
982       * @since 1.2
983       */
984 <    public synchronized boolean retainAll(Collection<?> c)  {
985 <        return super.retainAll(c);
984 >    public boolean retainAll(Collection<?> c) {
985 >        Objects.requireNonNull(c);
986 >        return bulkRemove(e -> !c.contains(e));
987 >    }
988 >
989 >    /**
990 >     * @throws NullPointerException {@inheritDoc}
991 >     */
992 >    @Override
993 >    public boolean removeIf(Predicate<? super E> filter) {
994 >        Objects.requireNonNull(filter);
995 >        return bulkRemove(filter);
996 >    }
997 >
998 >    // 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 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
1011 >        int expectedModCount = modCount;
1012 >        final Object[] es = elementData;
1013 >        final int end = elementCount;
1014 >        int i;
1015 >        // Optimize for initial run of survivors
1016 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
1017 >            ;
1018 >        // 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 >        if (i < end) {
1022 >            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 >            if (modCount != expectedModCount)
1029 >                throw new ConcurrentModificationException();
1030 >            expectedModCount++;
1031 >            modCount++;
1032 >            int w = beg;
1033 >            for (i = beg; i < end; i++)
1034 >                if (isClear(deathRow, i - beg))
1035 >                    es[w++] = es[i];
1036 >            for (i = elementCount = w; i < end; i++)
1037 >                es[i] = null;
1038 >            // checkInvariants();
1039 >            return true;
1040 >        } else {
1041 >            if (modCount != expectedModCount)
1042 >                throw new ConcurrentModificationException();
1043 >            // checkInvariants();
1044 >            return false;
1045 >        }
1046      }
1047  
1048      /**
# Line 895 | Line 1056 | public class Vector<E>
1056       * @param index index at which to insert the first element from the
1057       *              specified collection
1058       * @param c elements to be inserted into this Vector
1059 <     * @return <tt>true</tt> if this Vector changed as a result of the call
1060 <     * @exception ArrayIndexOutOfBoundsException index out of range (index
1061 <     *            &lt; 0 || index &gt; size())
1059 >     * @return {@code true} if this Vector changed as a result of the call
1060 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
1061 >     *         ({@code index < 0 || index > size()})
1062       * @throws NullPointerException if the specified collection is null
1063       * @since 1.2
1064       */
1065      public synchronized boolean addAll(int index, Collection<? extends E> c) {
1066 <        modCount++;
1067 <        if (index < 0 || index > elementCount)
907 <            throw new ArrayIndexOutOfBoundsException(index);
1066 >        if (index < 0 || index > elementCount)
1067 >            throw new ArrayIndexOutOfBoundsException(index);
1068  
1069          Object[] a = c.toArray();
1070 <        int numNew = a.length;
1071 <        ensureCapacityHelper(elementCount + numNew);
1072 <
1073 <        int numMoved = elementCount - index;
1074 <        if (numMoved > 0)
1075 <            System.arraycopy(elementData, index, elementData, index + numNew,
1076 <                             numMoved);
1077 <
1070 >        modCount++;
1071 >        int numNew = a.length;
1072 >        if (numNew == 0)
1073 >            return false;
1074 >        Object[] elementData = this.elementData;
1075 >        final int s = elementCount;
1076 >        if (numNew > elementData.length - s)
1077 >            elementData = grow(s + numNew);
1078 >
1079 >        int numMoved = s - index;
1080 >        if (numMoved > 0)
1081 >            System.arraycopy(elementData, index,
1082 >                             elementData, index + numNew,
1083 >                             numMoved);
1084          System.arraycopy(a, 0, elementData, index, numNew);
1085 <        elementCount += numNew;
1086 <        return numNew != 0;
1085 >        elementCount = s + numNew;
1086 >        // checkInvariants();
1087 >        return true;
1088      }
1089  
1090      /**
1091       * Compares the specified Object with this Vector for equality.  Returns
1092       * true if and only if the specified Object is also a List, both Lists
1093       * have the same size, and all corresponding pairs of elements in the two
1094 <     * Lists are <em>equal</em>.  (Two elements <code>e1</code> and
1095 <     * <code>e2</code> are <em>equal</em> if <code>(e1==null ? e2==null :
1096 <     * e1.equals(e2))</code>.)  In other words, two Lists are defined to be
1094 >     * Lists are <em>equal</em>.  (Two elements {@code e1} and
1095 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1096 >     * In other words, two Lists are defined to be
1097       * equal if they contain the same elements in the same order.
1098       *
1099       * @param o the Object to be compared for equality with this Vector
# Line 952 | Line 1119 | public class Vector<E>
1119      }
1120  
1121      /**
1122 <     * Removes from this List all of the elements whose index is between
1123 <     * fromIndex, inclusive and toIndex, exclusive.  Shifts any succeeding
1124 <     * elements to the left (reduces their index).
1125 <     * This call shortens the Vector by (toIndex - fromIndex) elements.  (If
1126 <     * toIndex==fromIndex, this operation has no effect.)
1122 >     * Returns a view of the portion of this List between fromIndex,
1123 >     * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1124 >     * equal, the returned List is empty.)  The returned List is backed by this
1125 >     * List, so changes in the returned List are reflected in this List, and
1126 >     * vice-versa.  The returned List supports all of the optional List
1127 >     * operations supported by this List.
1128       *
1129 <     * @param fromIndex index of first element to be removed
1130 <     * @param toIndex index after last element to be removed
1129 >     * <p>This method eliminates the need for explicit range operations (of
1130 >     * the sort that commonly exist for arrays).  Any operation that expects
1131 >     * a List can be used as a range operation by operating on a subList view
1132 >     * instead of a whole List.  For example, the following idiom
1133 >     * removes a range of elements from a List:
1134 >     * <pre>
1135 >     *      list.subList(from, to).clear();
1136 >     * </pre>
1137 >     * Similar idioms may be constructed for indexOf and lastIndexOf,
1138 >     * and all of the algorithms in the Collections class can be applied to
1139 >     * a subList.
1140 >     *
1141 >     * <p>The semantics of the List returned by this method become undefined if
1142 >     * the backing list (i.e., this List) is <i>structurally modified</i> in
1143 >     * any way other than via the returned List.  (Structural modifications are
1144 >     * those that change the size of the List, or otherwise perturb it in such
1145 >     * a fashion that iterations in progress may yield incorrect results.)
1146 >     *
1147 >     * @param fromIndex low endpoint (inclusive) of the subList
1148 >     * @param toIndex high endpoint (exclusive) of the subList
1149 >     * @return a view of the specified range within this List
1150 >     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1151 >     *         {@code (fromIndex < 0 || toIndex > size)}
1152 >     * @throws IllegalArgumentException if the endpoint indices are out of order
1153 >     *         {@code (fromIndex > toIndex)}
1154 >     */
1155 >    public synchronized List<E> subList(int fromIndex, int toIndex) {
1156 >        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1157 >                                            this);
1158 >    }
1159 >
1160 >    /**
1161 >     * Removes from this list all of the elements whose index is between
1162 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1163 >     * Shifts any succeeding elements to the left (reduces their index).
1164 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1165 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
1166       */
1167      protected synchronized void removeRange(int fromIndex, int toIndex) {
1168 <        modCount++;
1169 <        int numMoved = elementCount - toIndex;
1170 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1171 <                         numMoved);
1168 >        modCount++;
1169 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1170 >        // checkInvariants();
1171 >    }
1172  
1173 <        // Let gc do its work
1174 <        int newElementCount = elementCount - (toIndex-fromIndex);
1175 <        while (elementCount != newElementCount)
1176 <            elementData[--elementCount] = null;
1173 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1174 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1175 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1176 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1177 >            es[i] = null;
1178      }
1179  
1180      /**
1181 <     * Save the state of the <tt>Vector</tt> instance to a stream (that
1182 <     * is, serialize it).  This method is present merely for synchronization.
1183 <     * It just calls the default writeObject method.
1181 >     * Saves the state of the {@code Vector} instance to a stream
1182 >     * (that is, serializes it).
1183 >     * This method performs synchronization to ensure the consistency
1184 >     * of the serialized data.
1185 >     *
1186 >     * @param s the stream
1187 >     * @throws java.io.IOException if an I/O error occurs
1188       */
1189 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1190 <        throws java.io.IOException
1191 <    {
1192 <        s.defaultWriteObject();
1189 >    private void writeObject(java.io.ObjectOutputStream s)
1190 >            throws java.io.IOException {
1191 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1192 >        final Object[] data;
1193 >        synchronized (this) {
1194 >            fields.put("capacityIncrement", capacityIncrement);
1195 >            fields.put("elementCount", elementCount);
1196 >            data = elementData.clone();
1197 >        }
1198 >        fields.put("elementData", data);
1199 >        s.writeFields();
1200      }
1201  
1202      /**
1203 <     * Returns a list-iterator of the elements in this list (in proper
1203 >     * Returns a list iterator over the elements in this list (in proper
1204       * sequence), starting at the specified position in the list.
1205 <     * Obeys the general contract of {@link List#listIterator(int)}.
1205 >     * The specified index indicates the first element that would be
1206 >     * returned by an initial call to {@link ListIterator#next next}.
1207 >     * An initial call to {@link ListIterator#previous previous} would
1208 >     * return the element with the specified index minus one.
1209 >     *
1210 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1211       *
992     * <p>The list-iterator is <i>fail-fast</i>: if the list is structurally
993     * modified at any time after the Iterator is created, in any way except
994     * through the list-iterator's own {@code remove} or {@code add}
995     * methods, the list-iterator will throw a
996     * {@code ConcurrentModificationException}.  Thus, in the face of
997     * concurrent modification, the iterator fails quickly and cleanly, rather
998     * than risking arbitrary, non-deterministic behavior at an undetermined
999     * time in the future.
1000     *
1001     * @param index index of the first element to be returned from the
1002     *        list-iterator (by a call to {@link ListIterator#next})
1003     * @return a list-iterator of the elements in this list (in proper
1004     *         sequence), starting at the specified position in the list
1212       * @throws IndexOutOfBoundsException {@inheritDoc}
1213       */
1214      public synchronized ListIterator<E> listIterator(int index) {
1215 <        if (index < 0 || index > elementCount)
1215 >        if (index < 0 || index > elementCount)
1216              throw new IndexOutOfBoundsException("Index: "+index);
1217 <        return new VectorIterator(index, elementCount);
1217 >        return new ListItr(index);
1218      }
1219  
1220      /**
1221 <     * {@inheritDoc}
1221 >     * Returns a list iterator over the elements in this list (in proper
1222 >     * sequence).
1223 >     *
1224 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1225 >     *
1226 >     * @see #listIterator(int)
1227       */
1228      public synchronized ListIterator<E> listIterator() {
1229 <        return new VectorIterator(0, elementCount);
1229 >        return new ListItr(0);
1230      }
1231  
1232      /**
1233       * Returns an iterator over the elements in this list in proper sequence.
1234       *
1235 +     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1236 +     *
1237       * @return an iterator over the elements in this list in proper sequence
1238       */
1239      public synchronized Iterator<E> iterator() {
1240 <        return new VectorIterator(0, elementCount);
1027 <    }
1028 <
1029 <    /**
1030 <     * Helper method to access array elements under synchronization by
1031 <     * iterators. The caller performs index check with respect to
1032 <     * expected bounds, so errors accessing the element are reported
1033 <     * as ConcurrentModificationExceptions.
1034 <     */
1035 <    final synchronized Object iteratorGet(int index, int expectedModCount) {
1036 <        if (modCount == expectedModCount) {
1037 <            try {
1038 <                return elementData[index];
1039 <            } catch(IndexOutOfBoundsException fallThrough) {
1040 <            }
1041 <        }
1042 <        throw new ConcurrentModificationException();
1240 >        return new Itr();
1241      }
1242  
1243      /**
1244 <     * Streamlined specialization of AbstractList version of iterator.
1047 <     * Locally perfroms bounds checks, but relies on outer Vector
1048 <     * to access elements under synchronization.
1244 >     * An optimized version of AbstractList.Itr
1245       */
1246 <    private final class VectorIterator implements ListIterator<E> {
1247 <        int cursor;              // Index of next element to return;
1248 <        int fence;               // Upper bound on cursor (cache of size())
1249 <        int lastRet;             // Index of last element, or -1 if no such
1054 <        int expectedModCount;    // To check for CME
1246 >    private class Itr implements Iterator<E> {
1247 >        int cursor;       // index of next element to return
1248 >        int lastRet = -1; // index of last element returned; -1 if no such
1249 >        int expectedModCount = modCount;
1250  
1251 <        VectorIterator(int index, int fence) {
1252 <            this.cursor = index;
1253 <            this.fence = fence;
1254 <            this.lastRet = -1;
1060 <            this.expectedModCount = Vector.this.modCount;
1061 <        }
1062 <
1063 <        public boolean hasNext() {
1064 <            return cursor < fence;
1065 <        }
1066 <
1067 <        public boolean hasPrevious() {
1068 <            return cursor > 0;
1069 <        }
1070 <
1071 <        public int nextIndex() {
1072 <            return cursor;
1073 <        }
1074 <
1075 <        public int previousIndex() {
1076 <            return cursor - 1;
1077 <        }
1078 <
1079 <        public E next() {
1080 <            int i = cursor;
1081 <            if (i >= fence)
1082 <                throw new NoSuchElementException();
1083 <            Object next = Vector.this.iteratorGet(i, expectedModCount);
1084 <            lastRet = i;
1085 <            cursor = i + 1;
1086 <            return (E)next;
1087 <        }
1088 <
1089 <        public E previous() {
1090 <            int i = cursor - 1;
1091 <            if (i < 0)
1092 <                throw new NoSuchElementException();
1093 <            Object prev = Vector.this.iteratorGet(i, expectedModCount);
1094 <            lastRet = i;
1095 <            cursor = i;
1096 <            return (E)prev;
1251 >        public boolean hasNext() {
1252 >            // Racy but within spec, since modifications are checked
1253 >            // within or after synchronization in next/previous
1254 >            return cursor != elementCount;
1255          }
1256  
1257 <        public void set(E e) {
1258 <            if (lastRet < 0)
1259 <                throw new IllegalStateException();
1102 <            if (Vector.this.modCount != expectedModCount)
1103 <                throw new ConcurrentModificationException();
1104 <            try {
1105 <                Vector.this.set(lastRet, e);
1106 <                expectedModCount = Vector.this.modCount;
1107 <            } catch (IndexOutOfBoundsException ex) {
1108 <                throw new ConcurrentModificationException();
1109 <            }
1110 <        }
1111 <
1112 <        public void remove() {
1113 <            int i = lastRet;
1114 <            if (i < 0)
1115 <                throw new IllegalStateException();
1116 <            if (Vector.this.modCount != expectedModCount)
1117 <                throw new ConcurrentModificationException();
1118 <            try {
1119 <                Vector.this.remove(i);
1120 <                if (i < cursor)
1121 <                    cursor--;
1122 <                lastRet = -1;
1123 <                fence = Vector.this.size();
1124 <                expectedModCount = Vector.this.modCount;
1125 <            } catch (IndexOutOfBoundsException ex) {
1126 <                throw new ConcurrentModificationException();
1127 <            }
1128 <        }
1129 <
1130 <        public void add(E e) {
1131 <            if (Vector.this.modCount != expectedModCount)
1132 <                throw new ConcurrentModificationException();
1133 <            try {
1257 >        public E next() {
1258 >            synchronized (Vector.this) {
1259 >                checkForComodification();
1260                  int i = cursor;
1261 <                Vector.this.add(i, e);
1261 >                if (i >= elementCount)
1262 >                    throw new NoSuchElementException();
1263                  cursor = i + 1;
1264 <                lastRet = -1;
1138 <                fence = Vector.this.size();
1139 <                expectedModCount = Vector.this.modCount;
1140 <            } catch (IndexOutOfBoundsException ex) {
1141 <                throw new ConcurrentModificationException();
1142 <            }
1143 <        }
1144 <    }
1145 <
1146 <    /**
1147 <     * Returns a view of the portion of this List between fromIndex,
1148 <     * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1149 <     * equal, the returned List is empty.)  The returned List is backed by this
1150 <     * List, so changes in the returned List are reflected in this List, and
1151 <     * vice-versa.  The returned List supports all of the optional List
1152 <     * operations supported by this List.<p>
1153 <     *
1154 <     * This method eliminates the need for explicit range operations (of
1155 <     * the sort that commonly exist for arrays).   Any operation that expects
1156 <     * a List can be used as a range operation by operating on a subList view
1157 <     * instead of a whole List.  For example, the following idiom
1158 <     * removes a range of elements from a List:
1159 <     * <pre>
1160 <     *      list.subList(from, to).clear();
1161 <     * </pre>
1162 <     * Similar idioms may be constructed for indexOf and lastIndexOf,
1163 <     * and all of the algorithms in the Collections class can be applied to
1164 <     * a subList.<p>
1165 <     *
1166 <     * The semantics of the List returned by this method become undefined if
1167 <     * the backing list (i.e., this List) is <i>structurally modified</i> in
1168 <     * any way other than via the returned List.  (Structural modifications are
1169 <     * those that change the size of the List, or otherwise perturb it in such
1170 <     * a fashion that iterations in progress may yield incorrect results.)
1171 <     *
1172 <     * @param fromIndex low endpoint (inclusive) of the subList
1173 <     * @param toIndex high endpoint (exclusive) of the subList
1174 <     * @return a view of the specified range within this List
1175 <     * @throws IndexOutOfBoundsException endpoint index value out of range
1176 <     *         <code>(fromIndex &lt; 0 || toIndex &gt; size)</code>
1177 <     * @throws IllegalArgumentException endpoint indices out of order
1178 <     *         <code>(fromIndex &gt; toIndex)</code>
1179 <     */
1180 <    public synchronized List<E> subList(int fromIndex, int toIndex) {
1181 <        return new VectorSubList(this, this, fromIndex, fromIndex, toIndex);
1182 <    }
1183 <
1184 <    /**
1185 <     * This class specializes the AbstractList version of SubList to
1186 <     * avoid the double-indirection penalty that would arise using a
1187 <     * synchronized wrapper, as well as to avoid some unnecessary
1188 <     * checks in sublist iterators.
1189 <     */
1190 <    private static final class VectorSubList<E> extends AbstractList<E> implements RandomAccess {
1191 <        final Vector<E> base;             // base list
1192 <        final AbstractList<E> parent;     // Creating list
1193 <        final int baseOffset;             // index wrt Vector
1194 <        final int parentOffset;           // index wrt parent
1195 <        int length;                       // length of sublist
1196 <
1197 <        VectorSubList(Vector<E> base, AbstractList<E> parent, int baseOffset,
1198 <                     int fromIndex, int toIndex) {
1199 <            if (fromIndex < 0)
1200 <                throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
1201 <            if (toIndex > parent.size())
1202 <                throw new IndexOutOfBoundsException("toIndex = " + toIndex);
1203 <            if (fromIndex > toIndex)
1204 <                throw new IllegalArgumentException("fromIndex(" + fromIndex +
1205 <                                                   ") > toIndex(" + toIndex + ")");
1206 <
1207 <            this.base = base;
1208 <            this.parent = parent;
1209 <            this.baseOffset = baseOffset;
1210 <            this.parentOffset = fromIndex;
1211 <            this.length = toIndex - fromIndex;
1212 <            modCount = base.modCount;
1213 <        }
1214 <
1215 <        /**
1216 <         * Returns an IndexOutOfBoundsException with nicer message
1217 <         */
1218 <        private IndexOutOfBoundsException indexError(int index) {
1219 <            return new IndexOutOfBoundsException("Index: " + index +
1220 <                                                 ", Size: " + length);
1221 <        }
1222 <
1223 <        public E set(int index, E element) {
1224 <            synchronized(base) {
1225 <                if (index < 0 || index >= length)
1226 <                    throw indexError(index);
1227 <                if (base.modCount != modCount)
1228 <                    throw new ConcurrentModificationException();
1229 <                return base.set(index + baseOffset, element);
1230 <            }
1231 <        }
1232 <
1233 <        public E get(int index) {
1234 <            synchronized(base) {
1235 <                if (index < 0 || index >= length)
1236 <                    throw indexError(index);
1237 <                if (base.modCount != modCount)
1238 <                    throw new ConcurrentModificationException();
1239 <                return base.get(index + baseOffset);
1240 <            }
1241 <        }
1242 <
1243 <        public int size() {
1244 <            synchronized(base) {
1245 <                if (base.modCount != modCount)
1246 <                    throw new ConcurrentModificationException();
1247 <                return length;
1248 <            }
1249 <        }
1250 <
1251 <        public void add(int index, E element) {
1252 <            synchronized(base) {
1253 <                if (index < 0 || index > length)
1254 <                    throw indexError(index);
1255 <                if (base.modCount != modCount)
1256 <                    throw new ConcurrentModificationException();
1257 <                parent.add(index + parentOffset, element);
1258 <                length++;
1259 <                modCount = base.modCount;
1260 <            }
1261 <        }
1262 <
1263 <        public E remove(int index) {
1264 <            synchronized(base) {
1265 <                if (index < 0 || index >= length)
1266 <                    throw indexError(index);
1267 <                if (base.modCount != modCount)
1268 <                    throw new ConcurrentModificationException();
1269 <                E result = parent.remove(index + parentOffset);
1270 <                length--;
1271 <                modCount = base.modCount;
1272 <                return result;
1264 >                return elementData(lastRet = i);
1265              }
1266          }
1267  
1268 <        protected void removeRange(int fromIndex, int toIndex) {
1269 <            synchronized(base) {
1270 <                if (base.modCount != modCount)
1271 <                    throw new ConcurrentModificationException();
1272 <                parent.removeRange(fromIndex + parentOffset,
1273 <                                   toIndex + parentOffset);
1274 <                length -= (toIndex-fromIndex);
1283 <                modCount = base.modCount;
1268 >        public void remove() {
1269 >            if (lastRet == -1)
1270 >                throw new IllegalStateException();
1271 >            synchronized (Vector.this) {
1272 >                checkForComodification();
1273 >                Vector.this.remove(lastRet);
1274 >                expectedModCount = modCount;
1275              }
1276 +            cursor = lastRet;
1277 +            lastRet = -1;
1278          }
1279  
1280 <        public boolean addAll(Collection<? extends E> c) {
1281 <            return addAll(length, c);
1282 <        }
1283 <
1284 <        public boolean addAll(int index, Collection<? extends E> c) {
1285 <            synchronized(base) {
1286 <                if (index < 0 || index > length)
1287 <                    throw indexError(index);
1288 <                int cSize = c.size();
1289 <                if (cSize==0)
1290 <                    return false;
1298 <
1299 <                if (base.modCount != modCount)
1280 >        @Override
1281 >        public void forEachRemaining(Consumer<? super E> action) {
1282 >            Objects.requireNonNull(action);
1283 >            synchronized (Vector.this) {
1284 >                final int size = elementCount;
1285 >                int i = cursor;
1286 >                if (i >= size) {
1287 >                    return;
1288 >                }
1289 >                final Object[] es = elementData;
1290 >                if (i >= es.length)
1291                      throw new ConcurrentModificationException();
1292 <                parent.addAll(parentOffset + index, c);
1293 <                modCount = base.modCount;
1294 <                length += cSize;
1295 <                return true;
1292 >                while (i < size && modCount == expectedModCount)
1293 >                    action.accept(elementAt(es, i++));
1294 >                // update once at end of iteration to reduce heap write traffic
1295 >                cursor = i;
1296 >                lastRet = i - 1;
1297 >                checkForComodification();
1298              }
1299          }
1300  
1301 <        public boolean equals(Object o) {
1302 <            synchronized(base) {return super.equals(o);}
1301 >        final void checkForComodification() {
1302 >            if (modCount != expectedModCount)
1303 >                throw new ConcurrentModificationException();
1304          }
1305 +    }
1306  
1307 <        public int hashCode() {
1308 <            synchronized(base) {return super.hashCode();}
1307 >    /**
1308 >     * An optimized version of AbstractList.ListItr
1309 >     */
1310 >    final class ListItr extends Itr implements ListIterator<E> {
1311 >        ListItr(int index) {
1312 >            super();
1313 >            cursor = index;
1314          }
1315  
1316 <        public int indexOf(Object o) {
1317 <            synchronized(base) {return super.indexOf(o);}
1316 >        public boolean hasPrevious() {
1317 >            return cursor != 0;
1318          }
1319  
1320 <        public int lastIndexOf(Object o) {
1321 <            synchronized(base) {return super.lastIndexOf(o);}
1320 >        public int nextIndex() {
1321 >            return cursor;
1322          }
1323  
1324 <        public List<E> subList(int fromIndex, int toIndex) {
1325 <            return new VectorSubList(base, this, fromIndex + baseOffset,
1326 <                                     fromIndex, toIndex);
1324 >        public int previousIndex() {
1325 >            return cursor - 1;
1326          }
1327  
1328 <        public Iterator<E> iterator() {
1329 <            synchronized(base) {
1330 <                return new VectorSubListIterator(this, 0);
1328 >        public E previous() {
1329 >            synchronized (Vector.this) {
1330 >                checkForComodification();
1331 >                int i = cursor - 1;
1332 >                if (i < 0)
1333 >                    throw new NoSuchElementException();
1334 >                cursor = i;
1335 >                return elementData(lastRet = i);
1336              }
1337          }
1338  
1339 <        public synchronized ListIterator<E> listIterator() {
1340 <            synchronized(base) {
1341 <                return new VectorSubListIterator(this, 0);
1339 >        public void set(E e) {
1340 >            if (lastRet == -1)
1341 >                throw new IllegalStateException();
1342 >            synchronized (Vector.this) {
1343 >                checkForComodification();
1344 >                Vector.this.set(lastRet, e);
1345              }
1346          }
1347  
1348 <        public ListIterator<E> listIterator(int index) {
1349 <            synchronized(base) {
1350 <                if (index < 0 || index > length)
1351 <                    throw indexError(index);
1352 <                return new VectorSubListIterator(this, index);
1348 >        public void add(E e) {
1349 >            int i = cursor;
1350 >            synchronized (Vector.this) {
1351 >                checkForComodification();
1352 >                Vector.this.add(i, e);
1353 >                expectedModCount = modCount;
1354              }
1355 +            cursor = i + 1;
1356 +            lastRet = -1;
1357          }
1358 +    }
1359  
1360 <        /**
1361 <         * Same idea as VectorIterator, except routing structural
1362 <         * change operations through the sublist.
1363 <         */
1364 <        private static final class VectorSubListIterator<E> implements ListIterator<E> {
1365 <            final Vector<E> base;         // base list
1366 <            final VectorSubList<E> outer; // Sublist creating this iteraor
1367 <            final int offset;             // cursor offset wrt base
1368 <            int cursor;                   // Current index
1369 <            int fence;                    // Upper bound on cursor
1370 <            int lastRet;                  // Index of returned element, or -1
1371 <            int expectedModCount;         // Expected modCount of base Vector
1372 <
1373 <            VectorSubListIterator(VectorSubList<E> list, int index) {
1374 <                this.lastRet = -1;
1364 <                this.cursor = index;
1365 <                this.outer = list;
1366 <                this.offset = list.baseOffset;
1367 <                this.fence = list.length;
1368 <                this.base = list.base;
1369 <                this.expectedModCount = base.modCount;
1370 <            }
1360 >    /**
1361 >     * @throws NullPointerException {@inheritDoc}
1362 >     */
1363 >    @Override
1364 >    public synchronized void forEach(Consumer<? super E> action) {
1365 >        Objects.requireNonNull(action);
1366 >        final int expectedModCount = modCount;
1367 >        final Object[] es = elementData;
1368 >        final int size = elementCount;
1369 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1370 >            action.accept(elementAt(es, i));
1371 >        if (modCount != expectedModCount)
1372 >            throw new ConcurrentModificationException();
1373 >        // checkInvariants();
1374 >    }
1375  
1376 <            public boolean hasNext() {
1377 <                return cursor < fence;
1378 <            }
1376 >    /**
1377 >     * @throws NullPointerException {@inheritDoc}
1378 >     */
1379 >    @Override
1380 >    public synchronized void replaceAll(UnaryOperator<E> operator) {
1381 >        Objects.requireNonNull(operator);
1382 >        final int expectedModCount = modCount;
1383 >        final Object[] es = elementData;
1384 >        final int size = elementCount;
1385 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1386 >            es[i] = operator.apply(elementAt(es, i));
1387 >        if (modCount != expectedModCount)
1388 >            throw new ConcurrentModificationException();
1389 >        modCount++;
1390 >        // checkInvariants();
1391 >    }
1392  
1393 <            public boolean hasPrevious() {
1394 <                return cursor > 0;
1395 <            }
1393 >    @SuppressWarnings("unchecked")
1394 >    @Override
1395 >    public synchronized void sort(Comparator<? super E> c) {
1396 >        final int expectedModCount = modCount;
1397 >        Arrays.sort((E[]) elementData, 0, elementCount, c);
1398 >        if (modCount != expectedModCount)
1399 >            throw new ConcurrentModificationException();
1400 >        modCount++;
1401 >        // checkInvariants();
1402 >    }
1403  
1404 <            public int nextIndex() {
1405 <                return cursor;
1406 <            }
1404 >    /**
1405 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1406 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1407 >     * list.
1408 >     *
1409 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1410 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1411 >     * Overriding implementations should document the reporting of additional
1412 >     * characteristic values.
1413 >     *
1414 >     * @return a {@code Spliterator} over the elements in this list
1415 >     * @since 1.8
1416 >     */
1417 >    @Override
1418 >    public Spliterator<E> spliterator() {
1419 >        return new VectorSpliterator(null, 0, -1, 0);
1420 >    }
1421  
1422 <            public int previousIndex() {
1423 <                return cursor - 1;
1424 <            }
1422 >    /** Similar to ArrayList Spliterator */
1423 >    final class VectorSpliterator implements Spliterator<E> {
1424 >        private Object[] array;
1425 >        private int index; // current index, modified on advance/split
1426 >        private int fence; // -1 until used; then one past last index
1427 >        private int expectedModCount; // initialized when fence set
1428  
1429 <            public E next() {
1430 <                int i = cursor;
1431 <                if (cursor >= fence)
1432 <                    throw new NoSuchElementException();
1433 <                Object next = base.iteratorGet(i + offset, expectedModCount);
1434 <                lastRet = i;
1435 <                cursor = i + 1;
1436 <                return (E)next;
1396 <            }
1397 <
1398 <            public E previous() {
1399 <                int i = cursor - 1;
1400 <                if (i < 0)
1401 <                    throw new NoSuchElementException();
1402 <                Object prev = base.iteratorGet(i + offset, expectedModCount);
1403 <                lastRet = i;
1404 <                cursor = i;
1405 <                return (E)prev;
1406 <            }
1429 >        /** Creates new spliterator covering the given range. */
1430 >        VectorSpliterator(Object[] array, int origin, int fence,
1431 >                          int expectedModCount) {
1432 >            this.array = array;
1433 >            this.index = origin;
1434 >            this.fence = fence;
1435 >            this.expectedModCount = expectedModCount;
1436 >        }
1437  
1438 <            public void set(E e) {
1439 <                if (lastRet < 0)
1440 <                    throw new IllegalStateException();
1441 <                if (base.modCount != expectedModCount)
1442 <                    throw new ConcurrentModificationException();
1443 <                try {
1444 <                    outer.set(lastRet, e);
1415 <                    expectedModCount = base.modCount;
1416 <                } catch (IndexOutOfBoundsException ex) {
1417 <                    throw new ConcurrentModificationException();
1438 >        private int getFence() { // initialize on first use
1439 >            int hi;
1440 >            if ((hi = fence) < 0) {
1441 >                synchronized (Vector.this) {
1442 >                    array = elementData;
1443 >                    expectedModCount = modCount;
1444 >                    hi = fence = elementCount;
1445                  }
1446              }
1447 +            return hi;
1448 +        }
1449  
1450 <            public void remove() {
1451 <                int i = lastRet;
1452 <                if (i < 0)
1453 <                    throw new IllegalStateException();
1454 <                if (base.modCount != expectedModCount)
1455 <                    throw new ConcurrentModificationException();
1456 <                try {
1457 <                    outer.remove(i);
1458 <                    if (i < cursor)
1459 <                        cursor--;
1460 <                    lastRet = -1;
1461 <                    fence = outer.length;
1462 <                    expectedModCount = base.modCount;
1463 <                } catch (IndexOutOfBoundsException ex) {
1450 >        public Spliterator<E> trySplit() {
1451 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1452 >            return (lo >= mid) ? null :
1453 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1454 >        }
1455 >
1456 >        @SuppressWarnings("unchecked")
1457 >        public boolean tryAdvance(Consumer<? super E> action) {
1458 >            Objects.requireNonNull(action);
1459 >            int i;
1460 >            if (getFence() > (i = index)) {
1461 >                index = i + 1;
1462 >                action.accept((E)array[i]);
1463 >                if (modCount != expectedModCount)
1464                      throw new ConcurrentModificationException();
1465 <                }
1465 >                return true;
1466              }
1467 +            return false;
1468 +        }
1469  
1470 <            public void add(E e) {
1471 <                if (base.modCount != expectedModCount)
1472 <                    throw new ConcurrentModificationException();
1473 <                try {
1474 <                    int i = cursor;
1475 <                    outer.add(i, e);
1476 <                    cursor = i + 1;
1477 <                    lastRet = -1;
1478 <                    fence = outer.length;
1479 <                    expectedModCount = base.modCount;
1449 <                } catch (IndexOutOfBoundsException ex) {
1450 <                    throw new ConcurrentModificationException();
1451 <                }
1452 <            }
1470 >        @SuppressWarnings("unchecked")
1471 >        public void forEachRemaining(Consumer<? super E> action) {
1472 >            Objects.requireNonNull(action);
1473 >            final int hi = getFence();
1474 >            final Object[] a = array;
1475 >            int i;
1476 >            for (i = index, index = hi; i < hi; i++)
1477 >                action.accept((E) a[i]);
1478 >            if (modCount != expectedModCount)
1479 >                throw new ConcurrentModificationException();
1480          }
1454    }
1455 }
1481  
1482 +        public long estimateSize() {
1483 +            return getFence() - index;
1484 +        }
1485  
1486 +        public int characteristics() {
1487 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1488 +        }
1489 +    }
1490  
1491 +    void checkInvariants() {
1492 +        // assert elementCount >= 0;
1493 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1494 +    }
1495 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines