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.18 by jsr166, Mon Jun 26 00:25:04 2006 UTC vs.
Revision 1.56 by jsr166, Fri Aug 30 18:05:39 2019 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 1994, 2019, 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.io.IOException;
29 + import java.io.ObjectInputStream;
30 + import java.io.StreamCorruptedException;
31 + import java.util.function.Consumer;
32 + import java.util.function.Predicate;
33 + import java.util.function.UnaryOperator;
34 +
35 + import jdk.internal.util.ArraysSupport;
36 +
37   /**
38   * The {@code Vector} class implements a growable array of
39   * objects. Like an array, it contains components that can be
# Line 23 | Line 50 | package java.util;
50   * capacity of a vector before inserting a large number of
51   * components; this reduces the amount of incremental reallocation.
52   *
53 < * <p>The Iterators returned by Vector's iterator and listIterator
54 < * methods are <em>fail-fast</em>: if the Vector is structurally modified
55 < * at any time after the Iterator is created, in any way except through the
56 < * Iterator's own remove or add methods, the Iterator will throw a
57 < * ConcurrentModificationException.  Thus, in the face of concurrent
58 < * modification, the Iterator fails quickly and cleanly, rather than risking
59 < * arbitrary, non-deterministic behavior at an undetermined time in the future.
60 < * The Enumerations returned by Vector's elements method are <em>not</em>
61 < * fail-fast.
53 > * <p id="fail-fast">
54 > * The iterators returned by this class's {@link #iterator() iterator} and
55 > * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
56 > * if the vector is structurally modified at any time after the iterator is
57 > * created, in any way except through the iterator's own
58 > * {@link ListIterator#remove() remove} or
59 > * {@link ListIterator#add(Object) add} methods, the iterator will throw a
60 > * {@link ConcurrentModificationException}.  Thus, in the face of
61 > * concurrent modification, the iterator fails quickly and cleanly, rather
62 > * than risking arbitrary, non-deterministic behavior at an undetermined
63 > * time in the future.  The {@link Enumeration Enumerations} returned by
64 > * the {@link #elements() elements} method are <em>not</em> fail-fast; if the
65 > * Vector is structurally modified at any time after the enumeration is
66 > * created then the results of enumerating are undefined.
67   *
68   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
69   * as it is, generally speaking, impossible to make any hard guarantees in the
# Line 43 | Line 75 | package java.util;
75   *
76   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
77   * implement the {@link List} interface, making it a member of the
78 < * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
79 < * Collections Framework</a>.  Unlike the new collection
80 < * implementations, {@code Vector} is synchronized.
78 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
79 > * Java Collections Framework</a>.  Unlike the new collection
80 > * implementations, {@code Vector} is synchronized.  If a thread-safe
81 > * implementation is not needed, it is recommended to use {@link
82 > * ArrayList} in place of {@code Vector}.
83 > *
84 > * @param <E> Type of component elements
85   *
86   * @author  Lee Boynton
87   * @author  Jonathan Payne
52 * @version %I%, %G%
88   * @see Collection
54 * @see List
55 * @see ArrayList
89   * @see LinkedList
90 < * @since   JDK1.0
90 > * @since   1.0
91   */
92   public class Vector<E>
93      extends AbstractList<E>
# Line 91 | Line 124 | public class Vector<E>
124      protected int capacityIncrement;
125  
126      /** use serialVersionUID from JDK 1.0.2 for interoperability */
127 +    // OPENJDK @java.io.Serial
128      private static final long serialVersionUID = -2767605614048989439L;
129  
130      /**
# Line 104 | Line 138 | public class Vector<E>
138       *         is negative
139       */
140      public Vector(int initialCapacity, int capacityIncrement) {
141 <        super();
141 >        super();
142          if (initialCapacity < 0)
143              throw new IllegalArgumentException("Illegal Capacity: "+
144                                                 initialCapacity);
145 <        this.elementData = new Object[initialCapacity];
146 <        this.capacityIncrement = capacityIncrement;
145 >        this.elementData = new Object[initialCapacity];
146 >        this.capacityIncrement = capacityIncrement;
147      }
148  
149      /**
# Line 121 | Line 155 | public class Vector<E>
155       *         is negative
156       */
157      public Vector(int initialCapacity) {
158 <        this(initialCapacity, 0);
158 >        this(initialCapacity, 0);
159      }
160  
161      /**
# Line 130 | Line 164 | public class Vector<E>
164       * zero.
165       */
166      public Vector() {
167 <        this(10);
167 >        this(10);
168      }
169  
170      /**
# Line 144 | Line 178 | public class Vector<E>
178       * @since   1.2
179       */
180      public Vector(Collection<? extends E> c) {
181 <        elementData = c.toArray();
182 <        elementCount = elementData.length;
183 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
184 <        if (elementData.getClass() != Object[].class)
185 <            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
181 >        elementData = c.toArray();
182 >        elementCount = elementData.length;
183 >        // defend against c.toArray (incorrectly) not returning Object[]
184 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
185 >        if (elementData.getClass() != Object[].class)
186 >            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
187      }
188  
189      /**
# Line 165 | Line 200 | public class Vector<E>
200       * @see #toArray(Object[])
201       */
202      public synchronized void copyInto(Object[] anArray) {
203 <        System.arraycopy(elementData, 0, anArray, 0, elementCount);
203 >        System.arraycopy(elementData, 0, anArray, 0, elementCount);
204      }
205  
206      /**
# Line 177 | Line 212 | public class Vector<E>
212       * minimize the storage of a vector.
213       */
214      public synchronized void trimToSize() {
215 <        modCount++;
216 <        int oldCapacity = elementData.length;
217 <        if (elementCount < oldCapacity) {
215 >        modCount++;
216 >        int oldCapacity = elementData.length;
217 >        if (elementCount < oldCapacity) {
218              elementData = Arrays.copyOf(elementData, elementCount);
219 <        }
219 >        }
220      }
221  
222      /**
# Line 202 | Line 237 | public class Vector<E>
237       * @param minCapacity the desired minimum capacity
238       */
239      public synchronized void ensureCapacity(int minCapacity) {
240 <        modCount++;
241 <        ensureCapacityHelper(minCapacity);
240 >        if (minCapacity > 0) {
241 >            modCount++;
242 >            if (minCapacity > elementData.length)
243 >                grow(minCapacity);
244 >        }
245      }
246  
247      /**
248 <     * This implements the unsynchronized semantics of ensureCapacity.
249 <     * Synchronized methods in this class can internally call this
250 <     * method for ensuring capacity without incurring the cost of an
251 <     * extra synchronization.
252 <     *
253 <     * @see #ensureCapacity(int)
254 <     */
255 <    private void ensureCapacityHelper(int minCapacity) {
256 <        int oldCapacity = elementData.length;
257 <        if (minCapacity > oldCapacity) {
258 <            Object[] oldData = elementData;
259 <            int newCapacity = (capacityIncrement > 0) ?
260 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
261 <            if (newCapacity < minCapacity) {
262 <                newCapacity = minCapacity;
263 <            }
264 <            elementData = Arrays.copyOf(elementData, newCapacity);
227 <        }
248 >     * Increases the capacity to ensure that it can hold at least the
249 >     * number of elements specified by the minimum capacity argument.
250 >     *
251 >     * @param minCapacity the desired minimum capacity
252 >     * @throws OutOfMemoryError if minCapacity is less than zero
253 >     */
254 >    private Object[] grow(int minCapacity) {
255 >        int oldCapacity = elementData.length;
256 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
257 >                minCapacity - oldCapacity, /* minimum growth */
258 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
259 >                                           /* preferred growth */);
260 >        return elementData = Arrays.copyOf(elementData, newCapacity);
261 >    }
262 >
263 >    private Object[] grow() {
264 >        return grow(elementCount + 1);
265      }
266  
267      /**
# Line 237 | Line 274 | public class Vector<E>
274       * @throws ArrayIndexOutOfBoundsException if the new size is negative
275       */
276      public synchronized void setSize(int newSize) {
277 <        modCount++;
278 <        if (newSize > elementCount) {
279 <            ensureCapacityHelper(newSize);
280 <        } else {
281 <            for (int i = newSize ; i < elementCount ; i++) {
282 <                elementData[i] = null;
283 <            }
247 <        }
248 <        elementCount = newSize;
277 >        modCount++;
278 >        if (newSize > elementData.length)
279 >            grow(newSize);
280 >        final Object[] es = elementData;
281 >        for (int to = elementCount, i = newSize; i < to; i++)
282 >            es[i] = null;
283 >        elementCount = newSize;
284      }
285  
286      /**
# Line 256 | Line 291 | public class Vector<E>
291       *          of this vector)
292       */
293      public synchronized int capacity() {
294 <        return elementData.length;
294 >        return elementData.length;
295      }
296  
297      /**
# Line 265 | Line 300 | public class Vector<E>
300       * @return  the number of components in this vector
301       */
302      public synchronized int size() {
303 <        return elementCount;
303 >        return elementCount;
304      }
305  
306      /**
# Line 276 | Line 311 | public class Vector<E>
311       *          {@code false} otherwise.
312       */
313      public synchronized boolean isEmpty() {
314 <        return elementCount == 0;
314 >        return elementCount == 0;
315      }
316  
317      /**
318       * Returns an enumeration of the components of this vector. The
319       * returned {@code Enumeration} object will generate all items in
320       * this vector. The first item generated is the item at index {@code 0},
321 <     * then the item at index {@code 1}, and so on.
321 >     * then the item at index {@code 1}, and so on. If the vector is
322 >     * structurally modified while enumerating over the elements then the
323 >     * results of enumerating are undefined.
324       *
325       * @return  an enumeration of the components of this vector
326       * @see     Iterator
327       */
328      public Enumeration<E> elements() {
329 <        return new Enumeration<E>() {
330 <            int count = 0;
329 >        return new Enumeration<E>() {
330 >            int count = 0;
331 >
332 >            public boolean hasMoreElements() {
333 >                return count < elementCount;
334 >            }
335  
336 <            public boolean hasMoreElements() {
337 <                return count < elementCount;
338 <            }
339 <
340 <            public E nextElement() {
341 <                synchronized (Vector.this) {
342 <                    if (count < elementCount) {
343 <                        return (E)elementData[count++];
344 <                    }
304 <                }
305 <                throw new NoSuchElementException("Vector Enumeration");
306 <            }
307 <        };
336 >            public E nextElement() {
337 >                synchronized (Vector.this) {
338 >                    if (count < elementCount) {
339 >                        return elementData(count++);
340 >                    }
341 >                }
342 >                throw new NoSuchElementException("Vector Enumeration");
343 >            }
344 >        };
345      }
346  
347      /**
348       * Returns {@code true} if this vector contains the specified element.
349       * More formally, returns {@code true} if and only if this vector
350       * contains at least one element {@code e} such that
351 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
351 >     * {@code Objects.equals(o, e)}.
352       *
353       * @param o element whose presence in this vector is to be tested
354       * @return {@code true} if this vector contains the specified element
355       */
356      public boolean contains(Object o) {
357 <        return indexOf(o, 0) >= 0;
357 >        return indexOf(o, 0) >= 0;
358      }
359  
360      /**
361       * Returns the index of the first occurrence of the specified element
362       * in this vector, or -1 if this vector does not contain the element.
363       * More formally, returns the lowest index {@code i} such that
364 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
364 >     * {@code Objects.equals(o, get(i))},
365       * or -1 if there is no such index.
366       *
367       * @param o element to search for
# Line 332 | Line 369 | public class Vector<E>
369       *         this vector, or -1 if this vector does not contain the element
370       */
371      public int indexOf(Object o) {
372 <        return indexOf(o, 0);
372 >        return indexOf(o, 0);
373      }
374  
375      /**
# Line 340 | Line 377 | public class Vector<E>
377       * this vector, searching forwards from {@code index}, or returns -1 if
378       * the element is not found.
379       * More formally, returns the lowest index {@code i} such that
380 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
380 >     * {@code (i >= index && Objects.equals(o, get(i)))},
381       * or -1 if there is no such index.
382       *
383       * @param o element to search for
# Line 352 | Line 389 | public class Vector<E>
389       * @see     Object#equals(Object)
390       */
391      public synchronized int indexOf(Object o, int index) {
392 <        if (o == null) {
393 <            for (int i = index ; i < elementCount ; i++)
394 <                if (elementData[i]==null)
395 <                    return i;
396 <        } else {
397 <            for (int i = index ; i < elementCount ; i++)
398 <                if (o.equals(elementData[i]))
399 <                    return i;
400 <        }
401 <        return -1;
392 >        if (o == null) {
393 >            for (int i = index ; i < elementCount ; i++)
394 >                if (elementData[i]==null)
395 >                    return i;
396 >        } else {
397 >            for (int i = index ; i < elementCount ; i++)
398 >                if (o.equals(elementData[i]))
399 >                    return i;
400 >        }
401 >        return -1;
402      }
403  
404      /**
405       * Returns the index of the last occurrence of the specified element
406       * in this vector, or -1 if this vector does not contain the element.
407       * More formally, returns the highest index {@code i} such that
408 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
408 >     * {@code Objects.equals(o, get(i))},
409       * or -1 if there is no such index.
410       *
411       * @param o element to search for
# Line 376 | Line 413 | public class Vector<E>
413       *         this vector, or -1 if this vector does not contain the element
414       */
415      public synchronized int lastIndexOf(Object o) {
416 <        return lastIndexOf(o, elementCount-1);
416 >        return lastIndexOf(o, elementCount-1);
417      }
418  
419      /**
# Line 384 | Line 421 | public class Vector<E>
421       * this vector, searching backwards from {@code index}, or returns -1 if
422       * the element is not found.
423       * More formally, returns the highest index {@code i} such that
424 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
424 >     * {@code (i <= index && Objects.equals(o, get(i)))},
425       * or -1 if there is no such index.
426       *
427       * @param o element to search for
# Line 399 | Line 436 | public class Vector<E>
436          if (index >= elementCount)
437              throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
438  
439 <        if (o == null) {
440 <            for (int i = index; i >= 0; i--)
441 <                if (elementData[i]==null)
442 <                    return i;
443 <        } else {
444 <            for (int i = index; i >= 0; i--)
445 <                if (o.equals(elementData[i]))
446 <                    return i;
447 <        }
448 <        return -1;
439 >        if (o == null) {
440 >            for (int i = index; i >= 0; i--)
441 >                if (elementData[i]==null)
442 >                    return i;
443 >        } else {
444 >            for (int i = index; i >= 0; i--)
445 >                if (o.equals(elementData[i]))
446 >                    return i;
447 >        }
448 >        return -1;
449      }
450  
451      /**
# Line 420 | Line 457 | public class Vector<E>
457       * @param      index   an index into this vector
458       * @return     the component at the specified index
459       * @throws ArrayIndexOutOfBoundsException if the index is out of range
460 <     *         ({@code index < 0 || index >= size()})
460 >     *         ({@code index < 0 || index >= size()})
461       */
462      public synchronized E elementAt(int index) {
463 <        if (index >= elementCount) {
464 <            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
465 <        }
463 >        if (index >= elementCount) {
464 >            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
465 >        }
466  
467 <        return (E)elementData[index];
467 >        return elementData(index);
468      }
469  
470      /**
# Line 438 | Line 475 | public class Vector<E>
475       * @throws NoSuchElementException if this vector has no components
476       */
477      public synchronized E firstElement() {
478 <        if (elementCount == 0) {
479 <            throw new NoSuchElementException();
480 <        }
481 <        return (E)elementData[0];
478 >        if (elementCount == 0) {
479 >            throw new NoSuchElementException();
480 >        }
481 >        return elementData(0);
482      }
483  
484      /**
485       * Returns the last component of the vector.
486       *
487       * @return  the last component of the vector, i.e., the component at index
488 <     *          <code>size()&nbsp;-&nbsp;1</code>.
488 >     *          {@code size() - 1}
489       * @throws NoSuchElementException if this vector is empty
490       */
491      public synchronized E lastElement() {
492 <        if (elementCount == 0) {
493 <            throw new NoSuchElementException();
494 <        }
495 <        return (E)elementData[elementCount - 1];
492 >        if (elementCount == 0) {
493 >            throw new NoSuchElementException();
494 >        }
495 >        return elementData(elementCount - 1);
496      }
497  
498      /**
# Line 476 | Line 513 | public class Vector<E>
513       * @param      obj     what the component is to be set to
514       * @param      index   the specified index
515       * @throws ArrayIndexOutOfBoundsException if the index is out of range
516 <     *         ({@code index < 0 || index >= size()})
516 >     *         ({@code index < 0 || index >= size()})
517       */
518      public synchronized void setElementAt(E obj, int index) {
519 <        if (index >= elementCount) {
520 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
521 <                                                     elementCount);
522 <        }
523 <        elementData[index] = obj;
519 >        if (index >= elementCount) {
520 >            throw new ArrayIndexOutOfBoundsException(index + " >= " +
521 >                                                     elementCount);
522 >        }
523 >        elementData[index] = obj;
524      }
525  
526      /**
# Line 503 | Line 540 | public class Vector<E>
540       *
541       * @param      index   the index of the object to remove
542       * @throws ArrayIndexOutOfBoundsException if the index is out of range
543 <     *         ({@code index < 0 || index >= size()})
543 >     *         ({@code index < 0 || index >= size()})
544       */
545      public synchronized void removeElementAt(int index) {
546 <        modCount++;
547 <        if (index >= elementCount) {
548 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
549 <                                                     elementCount);
550 <        }
551 <        else if (index < 0) {
552 <            throw new ArrayIndexOutOfBoundsException(index);
553 <        }
554 <        int j = elementCount - index - 1;
555 <        if (j > 0) {
556 <            System.arraycopy(elementData, index + 1, elementData, index, j);
557 <        }
558 <        elementCount--;
559 <        elementData[elementCount] = null; /* to let gc do its work */
546 >        if (index >= elementCount) {
547 >            throw new ArrayIndexOutOfBoundsException(index + " >= " +
548 >                                                     elementCount);
549 >        }
550 >        else if (index < 0) {
551 >            throw new ArrayIndexOutOfBoundsException(index);
552 >        }
553 >        int j = elementCount - index - 1;
554 >        if (j > 0) {
555 >            System.arraycopy(elementData, index + 1, elementData, index, j);
556 >        }
557 >        modCount++;
558 >        elementCount--;
559 >        elementData[elementCount] = null; /* to let gc do its work */
560 >        // checkInvariants();
561      }
562  
563      /**
# Line 543 | Line 581 | public class Vector<E>
581       * @param      obj     the component to insert
582       * @param      index   where to insert the new component
583       * @throws ArrayIndexOutOfBoundsException if the index is out of range
584 <     *         ({@code index < 0 || index > size()})
584 >     *         ({@code index < 0 || index > size()})
585       */
586      public synchronized void insertElementAt(E obj, int index) {
587 <        modCount++;
588 <        if (index > elementCount) {
589 <            throw new ArrayIndexOutOfBoundsException(index
590 <                                                     + " > " + elementCount);
591 <        }
592 <        ensureCapacityHelper(elementCount + 1);
593 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
594 <        elementData[index] = obj;
595 <        elementCount++;
587 >        if (index > elementCount) {
588 >            throw new ArrayIndexOutOfBoundsException(index
589 >                                                     + " > " + elementCount);
590 >        }
591 >        modCount++;
592 >        final int s = elementCount;
593 >        Object[] elementData = this.elementData;
594 >        if (s == elementData.length)
595 >            elementData = grow();
596 >        System.arraycopy(elementData, index,
597 >                         elementData, index + 1,
598 >                         s - index);
599 >        elementData[index] = obj;
600 >        elementCount = s + 1;
601      }
602  
603      /**
# Line 569 | Line 612 | public class Vector<E>
612       * @param   obj   the component to be added
613       */
614      public synchronized void addElement(E obj) {
615 <        modCount++;
616 <        ensureCapacityHelper(elementCount + 1);
574 <        elementData[elementCount++] = obj;
615 >        modCount++;
616 >        add(obj, elementData, elementCount);
617      }
618  
619      /**
# Line 590 | Line 632 | public class Vector<E>
632       *          vector; {@code false} otherwise.
633       */
634      public synchronized boolean removeElement(Object obj) {
635 <        modCount++;
636 <        int i = indexOf(obj);
637 <        if (i >= 0) {
638 <            removeElementAt(i);
639 <            return true;
640 <        }
641 <        return false;
635 >        modCount++;
636 >        int i = indexOf(obj);
637 >        if (i >= 0) {
638 >            removeElementAt(i);
639 >            return true;
640 >        }
641 >        return false;
642      }
643  
644      /**
# Line 606 | Line 648 | public class Vector<E>
648       * method (which is part of the {@link List} interface).
649       */
650      public synchronized void removeAllElements() {
651 +        final Object[] es = elementData;
652 +        for (int to = elementCount, i = elementCount = 0; i < to; i++)
653 +            es[i] = null;
654          modCount++;
610        // Let gc do its work
611        for (int i = 0; i < elementCount; i++)
612            elementData[i] = null;
613
614        elementCount = 0;
655      }
656  
657      /**
# Line 622 | Line 662 | public class Vector<E>
662       * @return  a clone of this vector
663       */
664      public synchronized Object clone() {
665 <        try {
666 <            Vector<E> v = (Vector<E>) super.clone();
667 <            v.elementData = Arrays.copyOf(elementData, elementCount);
668 <            v.modCount = 0;
669 <            return v;
670 <        } catch (CloneNotSupportedException e) {
671 <            // this shouldn't happen, since we are Cloneable
672 <            throw new InternalError();
673 <        }
665 >        try {
666 >            @SuppressWarnings("unchecked")
667 >            Vector<E> v = (Vector<E>) super.clone();
668 >            v.elementData = Arrays.copyOf(elementData, elementCount);
669 >            v.modCount = 0;
670 >            return v;
671 >        } catch (CloneNotSupportedException e) {
672 >            // this shouldn't happen, since we are Cloneable
673 >            throw new InternalError(e);
674 >        }
675      }
676  
677      /**
# Line 657 | Line 698 | public class Vector<E>
698       * of the Vector <em>only</em> if the caller knows that the Vector
699       * does not contain any null elements.)
700       *
701 +     * @param <T> type of array elements. The same type as {@code <E>} or a
702 +     * supertype of {@code <E>}.
703       * @param a the array into which the elements of the Vector are to
704 <     *          be stored, if it is big enough; otherwise, a new array of the
705 <     *          same runtime type is allocated for this purpose.
704 >     *          be stored, if it is big enough; otherwise, a new array of the
705 >     *          same runtime type is allocated for this purpose.
706       * @return an array containing the elements of the Vector
707 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
708 <     * of the runtime type of every element in this Vector
707 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
708 >     * a supertype of the runtime type, {@code <E>}, of every element in this
709 >     * Vector
710       * @throws NullPointerException if the given array is null
711       * @since 1.2
712       */
713 +    @SuppressWarnings("unchecked")
714      public synchronized <T> T[] toArray(T[] a) {
715          if (a.length < elementCount)
716              return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
717  
718 <        System.arraycopy(elementData, 0, a, 0, elementCount);
718 >        System.arraycopy(elementData, 0, a, 0, elementCount);
719  
720          if (a.length > elementCount)
721              a[elementCount] = null;
# Line 680 | Line 725 | public class Vector<E>
725  
726      // Positional Access Operations
727  
728 +    @SuppressWarnings("unchecked")
729 +    E elementData(int index) {
730 +        return (E) elementData[index];
731 +    }
732 +
733 +    @SuppressWarnings("unchecked")
734 +    static <E> E elementAt(Object[] es, int index) {
735 +        return (E) es[index];
736 +    }
737 +
738      /**
739       * Returns the element at the specified position in this Vector.
740       *
# Line 690 | Line 745 | public class Vector<E>
745       * @since 1.2
746       */
747      public synchronized E get(int index) {
748 <        if (index >= elementCount)
749 <            throw new ArrayIndexOutOfBoundsException(index);
748 >        if (index >= elementCount)
749 >            throw new ArrayIndexOutOfBoundsException(index);
750  
751 <        return (E)elementData[index];
751 >        return elementData(index);
752      }
753  
754      /**
# Line 704 | Line 759 | public class Vector<E>
759       * @param element element to be stored at the specified position
760       * @return the element previously at the specified position
761       * @throws ArrayIndexOutOfBoundsException if the index is out of range
762 <     *         ({@code index < 0 || index >= size()})
762 >     *         ({@code index < 0 || index >= size()})
763       * @since 1.2
764       */
765      public synchronized E set(int index, E element) {
766 <        if (index >= elementCount)
767 <            throw new ArrayIndexOutOfBoundsException(index);
766 >        if (index >= elementCount)
767 >            throw new ArrayIndexOutOfBoundsException(index);
768  
769 <        Object oldValue = elementData[index];
770 <        elementData[index] = element;
771 <        return (E)oldValue;
769 >        E oldValue = elementData(index);
770 >        elementData[index] = element;
771 >        return oldValue;
772 >    }
773 >
774 >    /**
775 >     * This helper method split out from add(E) to keep method
776 >     * bytecode size under 35 (the -XX:MaxInlineSize default value),
777 >     * which helps when add(E) is called in a C1-compiled loop.
778 >     */
779 >    private void add(E e, Object[] elementData, int s) {
780 >        if (s == elementData.length)
781 >            elementData = grow();
782 >        elementData[s] = e;
783 >        elementCount = s + 1;
784 >        // checkInvariants();
785      }
786  
787      /**
# Line 724 | Line 792 | public class Vector<E>
792       * @since 1.2
793       */
794      public synchronized boolean add(E e) {
795 <        modCount++;
796 <        ensureCapacityHelper(elementCount + 1);
729 <        elementData[elementCount++] = e;
795 >        modCount++;
796 >        add(e, elementData, elementCount);
797          return true;
798      }
799  
# Line 734 | Line 801 | public class Vector<E>
801       * Removes the first occurrence of the specified element in this Vector
802       * If the Vector does not contain the element, it is unchanged.  More
803       * formally, removes the element with the lowest index i such that
804 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
804 >     * {@code Objects.equals(o, get(i))} (if such
805       * an element exists).
806       *
807       * @param o element to be removed from this Vector, if present
# Line 765 | Line 832 | public class Vector<E>
832       * Shifts any subsequent elements to the left (subtracts one from their
833       * indices).  Returns the element that was removed from the Vector.
834       *
768     * @throws ArrayIndexOutOfBoundsException if the index is out of range
769     *         ({@code index < 0 || index >= size()})
835       * @param index the index of the element to be removed
836       * @return element that was removed
837 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
838 +     *         ({@code index < 0 || index >= size()})
839       * @since 1.2
840       */
841      public synchronized E remove(int index) {
842 <        modCount++;
843 <        if (index >= elementCount)
844 <            throw new ArrayIndexOutOfBoundsException(index);
845 <        Object oldValue = elementData[index];
846 <
847 <        int numMoved = elementCount - index - 1;
848 <        if (numMoved > 0)
849 <            System.arraycopy(elementData, index+1, elementData, index,
850 <                             numMoved);
851 <        elementData[--elementCount] = null; // Let gc do its work
842 >        modCount++;
843 >        if (index >= elementCount)
844 >            throw new ArrayIndexOutOfBoundsException(index);
845 >        E oldValue = elementData(index);
846 >
847 >        int numMoved = elementCount - index - 1;
848 >        if (numMoved > 0)
849 >            System.arraycopy(elementData, index+1, elementData, index,
850 >                             numMoved);
851 >        elementData[--elementCount] = null; // Let gc do its work
852  
853 <        return (E)oldValue;
853 >        // checkInvariants();
854 >        return oldValue;
855      }
856  
857      /**
# Line 805 | Line 873 | public class Vector<E>
873       * @param   c a collection whose elements will be tested for containment
874       *          in this Vector
875       * @return true if this Vector contains all of the elements in the
876 <     *         specified collection
876 >     *         specified collection
877       * @throws NullPointerException if the specified collection is null
878       */
879      public synchronized boolean containsAll(Collection<?> c) {
# Line 825 | Line 893 | public class Vector<E>
893       * @throws NullPointerException if the specified collection is null
894       * @since 1.2
895       */
896 <    public synchronized boolean addAll(Collection<? extends E> c) {
829 <        modCount++;
896 >    public boolean addAll(Collection<? extends E> c) {
897          Object[] a = c.toArray();
898 +        modCount++;
899          int numNew = a.length;
900 <        ensureCapacityHelper(elementCount + numNew);
901 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
902 <        elementCount += numNew;
903 <        return numNew != 0;
900 >        if (numNew == 0)
901 >            return false;
902 >        synchronized (this) {
903 >            Object[] elementData = this.elementData;
904 >            final int s = elementCount;
905 >            if (numNew > elementData.length - s)
906 >                elementData = grow(s + numNew);
907 >            System.arraycopy(a, 0, elementData, s, numNew);
908 >            elementCount = s + numNew;
909 >            // checkInvariants();
910 >            return true;
911 >        }
912      }
913  
914      /**
# Line 843 | Line 919 | public class Vector<E>
919       * @return true if this Vector changed as a result of the call
920       * @throws ClassCastException if the types of one or more elements
921       *         in this vector are incompatible with the specified
922 <     *         collection (optional)
922 >     *         collection
923 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
924       * @throws NullPointerException if this vector contains one or more null
925       *         elements and the specified collection does not support null
926 <     *         elements (optional), or if the specified collection is null
926 >     *         elements
927 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
928 >     *         or if the specified collection is null
929       * @since 1.2
930       */
931 <    public synchronized boolean removeAll(Collection<?> c) {
932 <        return super.removeAll(c);
931 >    public boolean removeAll(Collection<?> c) {
932 >        Objects.requireNonNull(c);
933 >        return bulkRemove(e -> c.contains(e));
934      }
935  
936      /**
# Line 863 | Line 943 | public class Vector<E>
943       * @return true if this Vector changed as a result of the call
944       * @throws ClassCastException if the types of one or more elements
945       *         in this vector are incompatible with the specified
946 <     *         collection (optional)
946 >     *         collection
947 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
948       * @throws NullPointerException if this vector contains one or more null
949       *         elements and the specified collection does not support null
950 <     *         elements (optional), or if the specified collection is null
950 >     *         elements
951 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
952 >     *         or if the specified collection is null
953       * @since 1.2
954       */
955 <    public synchronized boolean retainAll(Collection<?> c)  {
956 <        return super.retainAll(c);
955 >    public boolean retainAll(Collection<?> c) {
956 >        Objects.requireNonNull(c);
957 >        return bulkRemove(e -> !c.contains(e));
958 >    }
959 >
960 >    /**
961 >     * @throws NullPointerException {@inheritDoc}
962 >     */
963 >    @Override
964 >    public boolean removeIf(Predicate<? super E> filter) {
965 >        Objects.requireNonNull(filter);
966 >        return bulkRemove(filter);
967 >    }
968 >
969 >    // A tiny bit set implementation
970 >
971 >    private static long[] nBits(int n) {
972 >        return new long[((n - 1) >> 6) + 1];
973 >    }
974 >    private static void setBit(long[] bits, int i) {
975 >        bits[i >> 6] |= 1L << i;
976 >    }
977 >    private static boolean isClear(long[] bits, int i) {
978 >        return (bits[i >> 6] & (1L << i)) == 0;
979 >    }
980 >
981 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
982 >        int expectedModCount = modCount;
983 >        final Object[] es = elementData;
984 >        final int end = elementCount;
985 >        int i;
986 >        // Optimize for initial run of survivors
987 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
988 >            ;
989 >        // Tolerate predicates that reentrantly access the collection for
990 >        // read (but writers still get CME), so traverse once to find
991 >        // elements to delete, a second pass to physically expunge.
992 >        if (i < end) {
993 >            final int beg = i;
994 >            final long[] deathRow = nBits(end - beg);
995 >            deathRow[0] = 1L;   // set bit 0
996 >            for (i = beg + 1; i < end; i++)
997 >                if (filter.test(elementAt(es, i)))
998 >                    setBit(deathRow, i - beg);
999 >            if (modCount != expectedModCount)
1000 >                throw new ConcurrentModificationException();
1001 >            modCount++;
1002 >            int w = beg;
1003 >            for (i = beg; i < end; i++)
1004 >                if (isClear(deathRow, i - beg))
1005 >                    es[w++] = es[i];
1006 >            for (i = elementCount = w; i < end; i++)
1007 >                es[i] = null;
1008 >            // checkInvariants();
1009 >            return true;
1010 >        } else {
1011 >            if (modCount != expectedModCount)
1012 >                throw new ConcurrentModificationException();
1013 >            // checkInvariants();
1014 >            return false;
1015 >        }
1016      }
1017  
1018      /**
# Line 891 | Line 1033 | public class Vector<E>
1033       * @since 1.2
1034       */
1035      public synchronized boolean addAll(int index, Collection<? extends E> c) {
1036 <        modCount++;
1037 <        if (index < 0 || index > elementCount)
896 <            throw new ArrayIndexOutOfBoundsException(index);
1036 >        if (index < 0 || index > elementCount)
1037 >            throw new ArrayIndexOutOfBoundsException(index);
1038  
1039          Object[] a = c.toArray();
1040 <        int numNew = a.length;
1041 <        ensureCapacityHelper(elementCount + numNew);
1042 <
1043 <        int numMoved = elementCount - index;
1044 <        if (numMoved > 0)
1045 <            System.arraycopy(elementData, index, elementData, index + numNew,
1046 <                             numMoved);
1047 <
1040 >        modCount++;
1041 >        int numNew = a.length;
1042 >        if (numNew == 0)
1043 >            return false;
1044 >        Object[] elementData = this.elementData;
1045 >        final int s = elementCount;
1046 >        if (numNew > elementData.length - s)
1047 >            elementData = grow(s + numNew);
1048 >
1049 >        int numMoved = s - index;
1050 >        if (numMoved > 0)
1051 >            System.arraycopy(elementData, index,
1052 >                             elementData, index + numNew,
1053 >                             numMoved);
1054          System.arraycopy(a, 0, elementData, index, numNew);
1055 <        elementCount += numNew;
1056 <        return numNew != 0;
1055 >        elementCount = s + numNew;
1056 >        // checkInvariants();
1057 >        return true;
1058      }
1059  
1060      /**
# Line 914 | Line 1062 | public class Vector<E>
1062       * true if and only if the specified Object is also a List, both Lists
1063       * have the same size, and all corresponding pairs of elements in the two
1064       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1065 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1066 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1065 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1066 >     * In other words, two Lists are defined to be
1067       * equal if they contain the same elements in the same order.
1068       *
1069       * @param o the Object to be compared for equality with this Vector
# Line 941 | Line 1089 | public class Vector<E>
1089      }
1090  
1091      /**
944     * Removes from this List all of the elements whose index is between
945     * fromIndex, inclusive and toIndex, exclusive.  Shifts any succeeding
946     * elements to the left (reduces their index).
947     * This call shortens the Vector by (toIndex - fromIndex) elements.  (If
948     * toIndex==fromIndex, this operation has no effect.)
949     *
950     * @param fromIndex index of first element to be removed
951     * @param toIndex index after last element to be removed
952     */
953    protected synchronized void removeRange(int fromIndex, int toIndex) {
954        modCount++;
955        int numMoved = elementCount - toIndex;
956        System.arraycopy(elementData, toIndex, elementData, fromIndex,
957                         numMoved);
958
959        // Let gc do its work
960        int newElementCount = elementCount - (toIndex-fromIndex);
961        while (elementCount != newElementCount)
962            elementData[--elementCount] = null;
963    }
964
965    /**
966     * Save the state of the {@code Vector} instance to a stream (that
967     * is, serialize it).  This method is present merely for synchronization.
968     * It just calls the default writeObject method.
969     */
970    private synchronized void writeObject(java.io.ObjectOutputStream s)
971        throws java.io.IOException
972    {
973        s.defaultWriteObject();
974    }
975
976    /**
977     * Returns a list-iterator of the elements in this list (in proper
978     * sequence), starting at the specified position in the list.
979     * Obeys the general contract of {@link List#listIterator(int)}.
980     *
981     * <p>The list-iterator is <i>fail-fast</i>: if the list is structurally
982     * modified at any time after the Iterator is created, in any way except
983     * through the list-iterator's own {@code remove} or {@code add}
984     * methods, the list-iterator will throw a
985     * {@code ConcurrentModificationException}.  Thus, in the face of
986     * concurrent modification, the iterator fails quickly and cleanly, rather
987     * than risking arbitrary, non-deterministic behavior at an undetermined
988     * time in the future.
989     *
990     * @param index index of the first element to be returned from the
991     *        list-iterator (by a call to {@link ListIterator#next})
992     * @return a list-iterator of the elements in this list (in proper
993     *         sequence), starting at the specified position in the list
994     * @throws IndexOutOfBoundsException {@inheritDoc}
995     */
996    public synchronized ListIterator<E> listIterator(int index) {
997        if (index < 0 || index > elementCount)
998            throw new IndexOutOfBoundsException("Index: "+index);
999        return new VectorIterator(index, elementCount);
1000    }
1001
1002    /**
1003     * {@inheritDoc}
1004     */
1005    public synchronized ListIterator<E> listIterator() {
1006        return new VectorIterator(0, elementCount);
1007    }
1008
1009    /**
1010     * Returns an iterator over the elements in this list in proper sequence.
1011     *
1012     * @return an iterator over the elements in this list in proper sequence
1013     */
1014    public synchronized Iterator<E> iterator() {
1015        return new VectorIterator(0, elementCount);
1016    }
1017
1018    /**
1019     * Helper method to access array elements under synchronization by
1020     * iterators. The caller performs index check with respect to
1021     * expected bounds, so errors accessing the element are reported
1022     * as ConcurrentModificationExceptions.
1023     */
1024    final synchronized Object iteratorGet(int index, int expectedModCount) {
1025        if (modCount == expectedModCount) {
1026            try {
1027                return elementData[index];
1028            } catch(IndexOutOfBoundsException fallThrough) {
1029            }
1030        }
1031        throw new ConcurrentModificationException();
1032    }
1033
1034    /**
1035     * Streamlined specialization of AbstractList version of iterator.
1036     * Locally perfroms bounds checks, but relies on outer Vector
1037     * to access elements under synchronization.
1038     */
1039    private final class VectorIterator implements ListIterator<E> {
1040        int cursor;              // Index of next element to return;
1041        int fence;               // Upper bound on cursor (cache of size())
1042        int lastRet;             // Index of last element, or -1 if no such
1043        int expectedModCount;    // To check for CME
1044
1045        VectorIterator(int index, int fence) {
1046            this.cursor = index;
1047            this.fence = fence;
1048            this.lastRet = -1;
1049            this.expectedModCount = Vector.this.modCount;
1050        }
1051
1052        public boolean hasNext() {
1053            return cursor < fence;
1054        }
1055
1056        public boolean hasPrevious() {
1057            return cursor > 0;
1058        }
1059
1060        public int nextIndex() {
1061            return cursor;
1062        }
1063
1064        public int previousIndex() {
1065            return cursor - 1;
1066        }
1067
1068        public E next() {
1069            int i = cursor;
1070            if (i >= fence)
1071                throw new NoSuchElementException();
1072            Object next = Vector.this.iteratorGet(i, expectedModCount);
1073            lastRet = i;
1074            cursor = i + 1;
1075            return (E)next;
1076        }
1077
1078        public E previous() {
1079            int i = cursor - 1;
1080            if (i < 0)
1081                throw new NoSuchElementException();
1082            Object prev = Vector.this.iteratorGet(i, expectedModCount);
1083            lastRet = i;
1084            cursor = i;
1085            return (E)prev;
1086        }
1087
1088        public void set(E e) {
1089            if (lastRet < 0)
1090                throw new IllegalStateException();
1091            if (Vector.this.modCount != expectedModCount)
1092                throw new ConcurrentModificationException();
1093            try {
1094                Vector.this.set(lastRet, e);
1095                expectedModCount = Vector.this.modCount;
1096            } catch (IndexOutOfBoundsException ex) {
1097                throw new ConcurrentModificationException();
1098            }
1099        }
1100
1101        public void remove() {
1102            int i = lastRet;
1103            if (i < 0)
1104                throw new IllegalStateException();
1105            if (Vector.this.modCount != expectedModCount)
1106                throw new ConcurrentModificationException();
1107            try {
1108                Vector.this.remove(i);
1109                if (i < cursor)
1110                    cursor--;
1111                lastRet = -1;
1112                fence = Vector.this.size();
1113                expectedModCount = Vector.this.modCount;
1114            } catch (IndexOutOfBoundsException ex) {
1115                throw new ConcurrentModificationException();
1116            }
1117        }
1118
1119        public void add(E e) {
1120            if (Vector.this.modCount != expectedModCount)
1121                throw new ConcurrentModificationException();
1122            try {
1123                int i = cursor;
1124                Vector.this.add(i, e);
1125                cursor = i + 1;
1126                lastRet = -1;
1127                fence = Vector.this.size();
1128                expectedModCount = Vector.this.modCount;
1129            } catch (IndexOutOfBoundsException ex) {
1130                throw new ConcurrentModificationException();
1131            }
1132        }
1133    }
1134
1135    /**
1092       * Returns a view of the portion of this List between fromIndex,
1093       * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1094       * equal, the returned List is empty.)  The returned List is backed by this
# Line 1141 | Line 1097 | public class Vector<E>
1097       * operations supported by this List.
1098       *
1099       * <p>This method eliminates the need for explicit range operations (of
1100 <     * the sort that commonly exist for arrays).   Any operation that expects
1100 >     * the sort that commonly exist for arrays).  Any operation that expects
1101       * a List can be used as a range operation by operating on a subList view
1102       * instead of a whole List.  For example, the following idiom
1103       * removes a range of elements from a List:
1104       * <pre>
1105 <     *      list.subList(from, to).clear();
1105 >     *      list.subList(from, to).clear();
1106       * </pre>
1107       * Similar idioms may be constructed for indexOf and lastIndexOf,
1108       * and all of the algorithms in the Collections class can be applied to
# Line 1164 | Line 1120 | public class Vector<E>
1120       * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1121       *         {@code (fromIndex < 0 || toIndex > size)}
1122       * @throws IllegalArgumentException if the endpoint indices are out of order
1123 <     *         {@code (fromIndex > toIndex)}
1123 >     *         {@code (fromIndex > toIndex)}
1124       */
1125      public synchronized List<E> subList(int fromIndex, int toIndex) {
1126 <        return new VectorSubList(this, this, fromIndex, fromIndex, toIndex);
1126 >        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1127 >                                            this);
1128      }
1129  
1130      /**
1131 <     * This class specializes the AbstractList version of SubList to
1132 <     * avoid the double-indirection penalty that would arise using a
1133 <     * synchronized wrapper, as well as to avoid some unnecessary
1134 <     * checks in sublist iterators.
1135 <     */
1136 <    private static final class VectorSubList<E> extends AbstractList<E> implements RandomAccess {
1137 <        final Vector<E> base;             // base list
1138 <        final AbstractList<E> parent;     // Creating list
1139 <        final int baseOffset;             // index wrt Vector
1140 <        final int parentOffset;           // index wrt parent
1141 <        int length;                       // length of sublist
1185 <
1186 <        VectorSubList(Vector<E> base, AbstractList<E> parent, int baseOffset,
1187 <                     int fromIndex, int toIndex) {
1188 <            if (fromIndex < 0)
1189 <                throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
1190 <            if (toIndex > parent.size())
1191 <                throw new IndexOutOfBoundsException("toIndex = " + toIndex);
1192 <            if (fromIndex > toIndex)
1193 <                throw new IllegalArgumentException("fromIndex(" + fromIndex +
1194 <                                                   ") > toIndex(" + toIndex + ")");
1195 <
1196 <            this.base = base;
1197 <            this.parent = parent;
1198 <            this.baseOffset = baseOffset;
1199 <            this.parentOffset = fromIndex;
1200 <            this.length = toIndex - fromIndex;
1201 <            modCount = base.modCount;
1202 <        }
1203 <
1204 <        /**
1205 <         * Returns an IndexOutOfBoundsException with nicer message
1206 <         */
1207 <        private IndexOutOfBoundsException indexError(int index) {
1208 <            return new IndexOutOfBoundsException("Index: " + index +
1209 <                                                 ", Size: " + length);
1210 <        }
1211 <
1212 <        public E set(int index, E element) {
1213 <            synchronized(base) {
1214 <                if (index < 0 || index >= length)
1215 <                    throw indexError(index);
1216 <                if (base.modCount != modCount)
1217 <                    throw new ConcurrentModificationException();
1218 <                return base.set(index + baseOffset, element);
1219 <            }
1220 <        }
1131 >     * Removes from this list all of the elements whose index is between
1132 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1133 >     * Shifts any succeeding elements to the left (reduces their index).
1134 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1135 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
1136 >     */
1137 >    protected synchronized void removeRange(int fromIndex, int toIndex) {
1138 >        modCount++;
1139 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1140 >        // checkInvariants();
1141 >    }
1142  
1143 <        public E get(int index) {
1144 <            synchronized(base) {
1145 <                if (index < 0 || index >= length)
1146 <                    throw indexError(index);
1147 <                if (base.modCount != modCount)
1148 <                    throw new ConcurrentModificationException();
1228 <                return base.get(index + baseOffset);
1229 <            }
1230 <        }
1143 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1144 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1145 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1146 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1147 >            es[i] = null;
1148 >    }
1149  
1150 <        public int size() {
1151 <            synchronized(base) {
1152 <                if (base.modCount != modCount)
1153 <                    throw new ConcurrentModificationException();
1154 <                return length;
1155 <            }
1150 >    /**
1151 >     * Loads a {@code Vector} instance from a stream
1152 >     * (that is, deserializes it).
1153 >     * This method performs checks to ensure the consistency
1154 >     * of the fields.
1155 >     *
1156 >     * @param in the stream
1157 >     * @throws java.io.IOException if an I/O error occurs
1158 >     * @throws ClassNotFoundException if the stream contains data
1159 >     *         of a non-existing class
1160 >     */
1161 >    // OPENJDK @java.io.Serial
1162 >    private void readObject(ObjectInputStream in)
1163 >            throws IOException, ClassNotFoundException {
1164 >        ObjectInputStream.GetField gfields = in.readFields();
1165 >        int count = gfields.get("elementCount", 0);
1166 >        Object[] data = (Object[])gfields.get("elementData", null);
1167 >        if (count < 0 || data == null || count > data.length) {
1168 >            throw new StreamCorruptedException("Inconsistent vector internals");
1169          }
1170 +        elementCount = count;
1171 +        elementData = data.clone();
1172 +    }
1173  
1174 <        public void add(int index, E element) {
1175 <            synchronized(base) {
1176 <                if (index < 0 || index > length)
1177 <                    throw indexError(index);
1178 <                if (base.modCount != modCount)
1179 <                    throw new ConcurrentModificationException();
1180 <                parent.add(index + parentOffset, element);
1181 <                length++;
1182 <                modCount = base.modCount;
1183 <            }
1174 >    /**
1175 >     * Saves the state of the {@code Vector} instance to a stream
1176 >     * (that is, serializes it).
1177 >     * This method performs synchronization to ensure the consistency
1178 >     * of the serialized data.
1179 >     *
1180 >     * @param s the stream
1181 >     * @throws java.io.IOException if an I/O error occurs
1182 >     */
1183 >    // OPENJDK @java.io.Serial
1184 >    private void writeObject(java.io.ObjectOutputStream s)
1185 >            throws java.io.IOException {
1186 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1187 >        final Object[] data;
1188 >        synchronized (this) {
1189 >            fields.put("capacityIncrement", capacityIncrement);
1190 >            fields.put("elementCount", elementCount);
1191 >            data = elementData.clone();
1192          }
1193 +        fields.put("elementData", data);
1194 +        s.writeFields();
1195 +    }
1196  
1197 <        public E remove(int index) {
1198 <            synchronized(base) {
1199 <                if (index < 0 || index >= length)
1200 <                    throw indexError(index);
1201 <                if (base.modCount != modCount)
1202 <                    throw new ConcurrentModificationException();
1203 <                E result = parent.remove(index + parentOffset);
1204 <                length--;
1205 <                modCount = base.modCount;
1206 <                return result;
1207 <            }
1197 >    /**
1198 >     * Returns a list iterator over the elements in this list (in proper
1199 >     * sequence), starting at the specified position in the list.
1200 >     * The specified index indicates the first element that would be
1201 >     * returned by an initial call to {@link ListIterator#next next}.
1202 >     * An initial call to {@link ListIterator#previous previous} would
1203 >     * return the element with the specified index minus one.
1204 >     *
1205 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1206 >     *
1207 >     * @throws IndexOutOfBoundsException {@inheritDoc}
1208 >     */
1209 >    public synchronized ListIterator<E> listIterator(int index) {
1210 >        if (index < 0 || index > elementCount)
1211 >            throw new IndexOutOfBoundsException("Index: "+index);
1212 >        return new ListItr(index);
1213 >    }
1214 >
1215 >    /**
1216 >     * Returns a list iterator over the elements in this list (in proper
1217 >     * sequence).
1218 >     *
1219 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1220 >     *
1221 >     * @see #listIterator(int)
1222 >     */
1223 >    public synchronized ListIterator<E> listIterator() {
1224 >        return new ListItr(0);
1225 >    }
1226 >
1227 >    /**
1228 >     * Returns an iterator over the elements in this list in proper sequence.
1229 >     *
1230 >     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1231 >     *
1232 >     * @return an iterator over the elements in this list in proper sequence
1233 >     */
1234 >    public synchronized Iterator<E> iterator() {
1235 >        return new Itr();
1236 >    }
1237 >
1238 >    /**
1239 >     * An optimized version of AbstractList.Itr
1240 >     */
1241 >    private class Itr implements Iterator<E> {
1242 >        int cursor;       // index of next element to return
1243 >        int lastRet = -1; // index of last element returned; -1 if no such
1244 >        int expectedModCount = modCount;
1245 >
1246 >        public boolean hasNext() {
1247 >            // Racy but within spec, since modifications are checked
1248 >            // within or after synchronization in next/previous
1249 >            return cursor != elementCount;
1250          }
1251  
1252 <        protected void removeRange(int fromIndex, int toIndex) {
1253 <            synchronized(base) {
1254 <                if (base.modCount != modCount)
1255 <                    throw new ConcurrentModificationException();
1256 <                parent.removeRange(fromIndex + parentOffset,
1257 <                                   toIndex + parentOffset);
1258 <                length -= (toIndex-fromIndex);
1259 <                modCount = base.modCount;
1252 >        public E next() {
1253 >            synchronized (Vector.this) {
1254 >                checkForComodification();
1255 >                int i = cursor;
1256 >                if (i >= elementCount)
1257 >                    throw new NoSuchElementException();
1258 >                cursor = i + 1;
1259 >                return elementData(lastRet = i);
1260              }
1261          }
1262  
1263 <        public boolean addAll(Collection<? extends E> c) {
1264 <            return addAll(length, c);
1263 >        public void remove() {
1264 >            if (lastRet == -1)
1265 >                throw new IllegalStateException();
1266 >            synchronized (Vector.this) {
1267 >                checkForComodification();
1268 >                Vector.this.remove(lastRet);
1269 >                expectedModCount = modCount;
1270 >            }
1271 >            cursor = lastRet;
1272 >            lastRet = -1;
1273          }
1274  
1275 <        public boolean addAll(int index, Collection<? extends E> c) {
1276 <            synchronized(base) {
1277 <                if (index < 0 || index > length)
1278 <                    throw indexError(index);
1279 <                int cSize = c.size();
1280 <                if (cSize==0)
1281 <                    return false;
1282 <
1283 <                if (base.modCount != modCount)
1275 >        @Override
1276 >        public void forEachRemaining(Consumer<? super E> action) {
1277 >            Objects.requireNonNull(action);
1278 >            synchronized (Vector.this) {
1279 >                final int size = elementCount;
1280 >                int i = cursor;
1281 >                if (i >= size) {
1282 >                    return;
1283 >                }
1284 >                final Object[] es = elementData;
1285 >                if (i >= es.length)
1286                      throw new ConcurrentModificationException();
1287 <                parent.addAll(parentOffset + index, c);
1288 <                modCount = base.modCount;
1289 <                length += cSize;
1290 <                return true;
1287 >                while (i < size && modCount == expectedModCount)
1288 >                    action.accept(elementAt(es, i++));
1289 >                // update once at end of iteration to reduce heap write traffic
1290 >                cursor = i;
1291 >                lastRet = i - 1;
1292 >                checkForComodification();
1293              }
1294          }
1295  
1296 <        public boolean equals(Object o) {
1297 <            synchronized(base) {return super.equals(o);}
1296 >        final void checkForComodification() {
1297 >            if (modCount != expectedModCount)
1298 >                throw new ConcurrentModificationException();
1299          }
1300 +    }
1301  
1302 <        public int hashCode() {
1303 <            synchronized(base) {return super.hashCode();}
1302 >    /**
1303 >     * An optimized version of AbstractList.ListItr
1304 >     */
1305 >    final class ListItr extends Itr implements ListIterator<E> {
1306 >        ListItr(int index) {
1307 >            super();
1308 >            cursor = index;
1309          }
1310  
1311 <        public int indexOf(Object o) {
1312 <            synchronized(base) {return super.indexOf(o);}
1311 >        public boolean hasPrevious() {
1312 >            return cursor != 0;
1313          }
1314  
1315 <        public int lastIndexOf(Object o) {
1316 <            synchronized(base) {return super.lastIndexOf(o);}
1315 >        public int nextIndex() {
1316 >            return cursor;
1317          }
1318  
1319 <        public List<E> subList(int fromIndex, int toIndex) {
1320 <            return new VectorSubList(base, this, fromIndex + baseOffset,
1315 <                                     fromIndex, toIndex);
1319 >        public int previousIndex() {
1320 >            return cursor - 1;
1321          }
1322  
1323 <        public Iterator<E> iterator() {
1324 <            synchronized(base) {
1325 <                return new VectorSubListIterator(this, 0);
1323 >        public E previous() {
1324 >            synchronized (Vector.this) {
1325 >                checkForComodification();
1326 >                int i = cursor - 1;
1327 >                if (i < 0)
1328 >                    throw new NoSuchElementException();
1329 >                cursor = i;
1330 >                return elementData(lastRet = i);
1331              }
1332          }
1333  
1334 <        public synchronized ListIterator<E> listIterator() {
1335 <            synchronized(base) {
1336 <                return new VectorSubListIterator(this, 0);
1334 >        public void set(E e) {
1335 >            if (lastRet == -1)
1336 >                throw new IllegalStateException();
1337 >            synchronized (Vector.this) {
1338 >                checkForComodification();
1339 >                Vector.this.set(lastRet, e);
1340              }
1341          }
1342  
1343 <        public ListIterator<E> listIterator(int index) {
1344 <            synchronized(base) {
1345 <                if (index < 0 || index > length)
1346 <                    throw indexError(index);
1347 <                return new VectorSubListIterator(this, index);
1343 >        public void add(E e) {
1344 >            int i = cursor;
1345 >            synchronized (Vector.this) {
1346 >                checkForComodification();
1347 >                Vector.this.add(i, e);
1348 >                expectedModCount = modCount;
1349              }
1350 +            cursor = i + 1;
1351 +            lastRet = -1;
1352          }
1353 +    }
1354  
1355 <        /**
1356 <         * Same idea as VectorIterator, except routing structural
1357 <         * change operations through the sublist.
1358 <         */
1359 <        private static final class VectorSubListIterator<E> implements ListIterator<E> {
1360 <            final Vector<E> base;         // base list
1361 <            final VectorSubList<E> outer; // Sublist creating this iteraor
1362 <            final int offset;             // cursor offset wrt base
1363 <            int cursor;                   // Current index
1364 <            int fence;                    // Upper bound on cursor
1365 <            int lastRet;                  // Index of returned element, or -1
1366 <            int expectedModCount;         // Expected modCount of base Vector
1367 <
1368 <            VectorSubListIterator(VectorSubList<E> list, int index) {
1369 <                this.lastRet = -1;
1353 <                this.cursor = index;
1354 <                this.outer = list;
1355 <                this.offset = list.baseOffset;
1356 <                this.fence = list.length;
1357 <                this.base = list.base;
1358 <                this.expectedModCount = base.modCount;
1359 <            }
1360 <
1361 <            public boolean hasNext() {
1362 <                return cursor < fence;
1363 <            }
1355 >    /**
1356 >     * @throws NullPointerException {@inheritDoc}
1357 >     */
1358 >    @Override
1359 >    public synchronized void forEach(Consumer<? super E> action) {
1360 >        Objects.requireNonNull(action);
1361 >        final int expectedModCount = modCount;
1362 >        final Object[] es = elementData;
1363 >        final int size = elementCount;
1364 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1365 >            action.accept(elementAt(es, i));
1366 >        if (modCount != expectedModCount)
1367 >            throw new ConcurrentModificationException();
1368 >        // checkInvariants();
1369 >    }
1370  
1371 <            public boolean hasPrevious() {
1372 <                return cursor > 0;
1373 <            }
1371 >    /**
1372 >     * @throws NullPointerException {@inheritDoc}
1373 >     */
1374 >    @Override
1375 >    public synchronized void replaceAll(UnaryOperator<E> operator) {
1376 >        Objects.requireNonNull(operator);
1377 >        final int expectedModCount = modCount;
1378 >        final Object[] es = elementData;
1379 >        final int size = elementCount;
1380 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1381 >            es[i] = operator.apply(elementAt(es, i));
1382 >        if (modCount != expectedModCount)
1383 >            throw new ConcurrentModificationException();
1384 >        // TODO(8203662): remove increment of modCount from ...
1385 >        modCount++;
1386 >        // checkInvariants();
1387 >    }
1388  
1389 <            public int nextIndex() {
1390 <                return cursor;
1391 <            }
1389 >    @SuppressWarnings("unchecked")
1390 >    @Override
1391 >    public synchronized void sort(Comparator<? super E> c) {
1392 >        final int expectedModCount = modCount;
1393 >        Arrays.sort((E[]) elementData, 0, elementCount, c);
1394 >        if (modCount != expectedModCount)
1395 >            throw new ConcurrentModificationException();
1396 >        modCount++;
1397 >        // checkInvariants();
1398 >    }
1399  
1400 <            public int previousIndex() {
1401 <                return cursor - 1;
1402 <            }
1400 >    /**
1401 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1402 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1403 >     * list.
1404 >     *
1405 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1406 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1407 >     * Overriding implementations should document the reporting of additional
1408 >     * characteristic values.
1409 >     *
1410 >     * @return a {@code Spliterator} over the elements in this list
1411 >     * @since 1.8
1412 >     */
1413 >    @Override
1414 >    public Spliterator<E> spliterator() {
1415 >        return new VectorSpliterator(null, 0, -1, 0);
1416 >    }
1417  
1418 <            public E next() {
1419 <                int i = cursor;
1420 <                if (cursor >= fence)
1421 <                    throw new NoSuchElementException();
1422 <                Object next = base.iteratorGet(i + offset, expectedModCount);
1423 <                lastRet = i;
1383 <                cursor = i + 1;
1384 <                return (E)next;
1385 <            }
1418 >    /** Similar to ArrayList Spliterator */
1419 >    final class VectorSpliterator implements Spliterator<E> {
1420 >        private Object[] array;
1421 >        private int index; // current index, modified on advance/split
1422 >        private int fence; // -1 until used; then one past last index
1423 >        private int expectedModCount; // initialized when fence set
1424  
1425 <            public E previous() {
1426 <                int i = cursor - 1;
1427 <                if (i < 0)
1428 <                    throw new NoSuchElementException();
1429 <                Object prev = base.iteratorGet(i + offset, expectedModCount);
1430 <                lastRet = i;
1431 <                cursor = i;
1432 <                return (E)prev;
1395 <            }
1425 >        /** Creates new spliterator covering the given range. */
1426 >        VectorSpliterator(Object[] array, int origin, int fence,
1427 >                          int expectedModCount) {
1428 >            this.array = array;
1429 >            this.index = origin;
1430 >            this.fence = fence;
1431 >            this.expectedModCount = expectedModCount;
1432 >        }
1433  
1434 <            public void set(E e) {
1435 <                if (lastRet < 0)
1436 <                    throw new IllegalStateException();
1437 <                if (base.modCount != expectedModCount)
1438 <                    throw new ConcurrentModificationException();
1439 <                try {
1440 <                    outer.set(lastRet, e);
1404 <                    expectedModCount = base.modCount;
1405 <                } catch (IndexOutOfBoundsException ex) {
1406 <                    throw new ConcurrentModificationException();
1434 >        private int getFence() { // initialize on first use
1435 >            int hi;
1436 >            if ((hi = fence) < 0) {
1437 >                synchronized (Vector.this) {
1438 >                    array = elementData;
1439 >                    expectedModCount = modCount;
1440 >                    hi = fence = elementCount;
1441                  }
1442              }
1443 +            return hi;
1444 +        }
1445  
1446 <            public void remove() {
1447 <                int i = lastRet;
1448 <                if (i < 0)
1449 <                    throw new IllegalStateException();
1450 <                if (base.modCount != expectedModCount)
1446 >        public Spliterator<E> trySplit() {
1447 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1448 >            return (lo >= mid) ? null :
1449 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1450 >        }
1451 >
1452 >        @SuppressWarnings("unchecked")
1453 >        public boolean tryAdvance(Consumer<? super E> action) {
1454 >            Objects.requireNonNull(action);
1455 >            int i;
1456 >            if (getFence() > (i = index)) {
1457 >                index = i + 1;
1458 >                action.accept((E)array[i]);
1459 >                if (modCount != expectedModCount)
1460                      throw new ConcurrentModificationException();
1461 <                try {
1417 <                    outer.remove(i);
1418 <                    if (i < cursor)
1419 <                        cursor--;
1420 <                    lastRet = -1;
1421 <                    fence = outer.length;
1422 <                    expectedModCount = base.modCount;
1423 <                } catch (IndexOutOfBoundsException ex) {
1424 <                    throw new ConcurrentModificationException();
1425 <                }
1461 >                return true;
1462              }
1463 +            return false;
1464 +        }
1465  
1466 <            public void add(E e) {
1467 <                if (base.modCount != expectedModCount)
1468 <                    throw new ConcurrentModificationException();
1469 <                try {
1470 <                    int i = cursor;
1471 <                    outer.add(i, e);
1472 <                    cursor = i + 1;
1473 <                    lastRet = -1;
1474 <                    fence = outer.length;
1475 <                    expectedModCount = base.modCount;
1438 <                } catch (IndexOutOfBoundsException ex) {
1439 <                    throw new ConcurrentModificationException();
1440 <                }
1441 <            }
1466 >        @SuppressWarnings("unchecked")
1467 >        public void forEachRemaining(Consumer<? super E> action) {
1468 >            Objects.requireNonNull(action);
1469 >            final int hi = getFence();
1470 >            final Object[] a = array;
1471 >            int i;
1472 >            for (i = index, index = hi; i < hi; i++)
1473 >                action.accept((E) a[i]);
1474 >            if (modCount != expectedModCount)
1475 >                throw new ConcurrentModificationException();
1476          }
1443    }
1444 }
1477  
1478 +        public long estimateSize() {
1479 +            return getFence() - index;
1480 +        }
1481  
1482 +        public int characteristics() {
1483 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1484 +        }
1485 +    }
1486  
1487 +    void checkInvariants() {
1488 +        // assert elementCount >= 0;
1489 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1490 +    }
1491 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines