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.20 by jsr166, Sun Jan 7 07:38:27 2007 UTC vs.
Revision 1.54 by jsr166, Thu May 2 14:31:30 2019 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 1994, 2018, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2007 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   /**
36   * The {@code Vector} class implements a growable array of
37   * objects. Like an array, it contains components that can be
# Line 23 | Line 48 | package java.util;
48   * capacity of a vector before inserting a large number of
49   * components; this reduces the amount of incremental reallocation.
50   *
51 < * <p>The Iterators returned by Vector's iterator and listIterator
52 < * methods are <em>fail-fast</em>: if the Vector is structurally modified
53 < * at any time after the Iterator is created, in any way except through the
54 < * Iterator's own remove or add methods, the Iterator will throw a
55 < * ConcurrentModificationException.  Thus, in the face of concurrent
56 < * modification, the Iterator fails quickly and cleanly, rather than risking
57 < * arbitrary, non-deterministic behavior at an undetermined time in the future.
58 < * The Enumerations returned by Vector's elements method are <em>not</em>
59 < * fail-fast.
51 > * <p id="fail-fast">
52 > * The iterators returned by this class's {@link #iterator() iterator} and
53 > * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
54 > * if the vector is structurally modified at any time after the iterator is
55 > * created, in any way except through the iterator's own
56 > * {@link ListIterator#remove() remove} or
57 > * {@link ListIterator#add(Object) add} methods, the iterator will throw a
58 > * {@link ConcurrentModificationException}.  Thus, in the face of
59 > * concurrent modification, the iterator fails quickly and cleanly, rather
60 > * than risking arbitrary, non-deterministic behavior at an undetermined
61 > * time in the future.  The {@link Enumeration Enumerations} returned by
62 > * the {@link #elements() elements} method are <em>not</em> fail-fast; if the
63 > * Vector is structurally modified at any time after the enumeration is
64 > * created then the results of enumerating are undefined.
65   *
66   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
67   * as it is, generally speaking, impossible to make any hard guarantees in the
# Line 43 | Line 73 | package java.util;
73   *
74   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
75   * implement the {@link List} interface, making it a member of the
76 < * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
77 < * Collections Framework</a>.  Unlike the new collection
78 < * implementations, {@code Vector} is synchronized.
76 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
77 > * Java Collections Framework</a>.  Unlike the new collection
78 > * implementations, {@code Vector} is synchronized.  If a thread-safe
79 > * implementation is not needed, it is recommended to use {@link
80 > * ArrayList} in place of {@code Vector}.
81 > *
82 > * @param <E> Type of component elements
83   *
84   * @author  Lee Boynton
85   * @author  Jonathan Payne
52 * @version %I%, %G%
86   * @see Collection
54 * @see List
55 * @see ArrayList
87   * @see LinkedList
88 < * @since   JDK1.0
88 > * @since   1.0
89   */
90   public class Vector<E>
91      extends AbstractList<E>
# Line 104 | Line 135 | public class Vector<E>
135       *         is negative
136       */
137      public Vector(int initialCapacity, int capacityIncrement) {
138 <        super();
138 >        super();
139          if (initialCapacity < 0)
140              throw new IllegalArgumentException("Illegal Capacity: "+
141                                                 initialCapacity);
142 <        this.elementData = new Object[initialCapacity];
143 <        this.capacityIncrement = capacityIncrement;
142 >        this.elementData = new Object[initialCapacity];
143 >        this.capacityIncrement = capacityIncrement;
144      }
145  
146      /**
# Line 121 | Line 152 | public class Vector<E>
152       *         is negative
153       */
154      public Vector(int initialCapacity) {
155 <        this(initialCapacity, 0);
155 >        this(initialCapacity, 0);
156      }
157  
158      /**
# Line 130 | Line 161 | public class Vector<E>
161       * zero.
162       */
163      public Vector() {
164 <        this(10);
164 >        this(10);
165      }
166  
167      /**
# Line 144 | Line 175 | public class Vector<E>
175       * @since   1.2
176       */
177      public Vector(Collection<? extends E> c) {
178 <        elementData = c.toArray();
179 <        elementCount = elementData.length;
180 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
181 <        if (elementData.getClass() != Object[].class)
182 <            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
178 >        elementData = c.toArray();
179 >        elementCount = elementData.length;
180 >        // defend against c.toArray (incorrectly) not returning Object[]
181 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
182 >        if (elementData.getClass() != Object[].class)
183 >            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
184      }
185  
186      /**
# Line 165 | Line 197 | public class Vector<E>
197       * @see #toArray(Object[])
198       */
199      public synchronized void copyInto(Object[] anArray) {
200 <        System.arraycopy(elementData, 0, anArray, 0, elementCount);
200 >        System.arraycopy(elementData, 0, anArray, 0, elementCount);
201      }
202  
203      /**
# Line 177 | Line 209 | public class Vector<E>
209       * minimize the storage of a vector.
210       */
211      public synchronized void trimToSize() {
212 <        modCount++;
213 <        int oldCapacity = elementData.length;
214 <        if (elementCount < oldCapacity) {
212 >        modCount++;
213 >        int oldCapacity = elementData.length;
214 >        if (elementCount < oldCapacity) {
215              elementData = Arrays.copyOf(elementData, elementCount);
216 <        }
216 >        }
217      }
218  
219      /**
# Line 202 | Line 234 | public class Vector<E>
234       * @param minCapacity the desired minimum capacity
235       */
236      public synchronized void ensureCapacity(int minCapacity) {
237 <        modCount++;
238 <        ensureCapacityHelper(minCapacity);
237 >        if (minCapacity > 0) {
238 >            modCount++;
239 >            if (minCapacity > elementData.length)
240 >                grow(minCapacity);
241 >        }
242 >    }
243 >
244 >    /**
245 >     * The maximum size of array to allocate (unless necessary).
246 >     * Some VMs reserve some header words in an array.
247 >     * Attempts to allocate larger arrays may result in
248 >     * OutOfMemoryError: Requested array size exceeds VM limit
249 >     */
250 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
251 >
252 >    /**
253 >     * Increases the capacity to ensure that it can hold at least the
254 >     * number of elements specified by the minimum capacity argument.
255 >     *
256 >     * @param minCapacity the desired minimum capacity
257 >     * @throws OutOfMemoryError if minCapacity is less than zero
258 >     */
259 >    private Object[] grow(int minCapacity) {
260 >        return elementData = Arrays.copyOf(elementData,
261 >                                           newCapacity(minCapacity));
262 >    }
263 >
264 >    private Object[] grow() {
265 >        return grow(elementCount + 1);
266      }
267  
268      /**
269 <     * This implements the unsynchronized semantics of ensureCapacity.
270 <     * Synchronized methods in this class can internally call this
271 <     * method for ensuring capacity without incurring the cost of an
272 <     * extra synchronization.
273 <     *
274 <     * @see #ensureCapacity(int)
275 <     */
276 <    private void ensureCapacityHelper(int minCapacity) {
277 <        int oldCapacity = elementData.length;
278 <        if (minCapacity > oldCapacity) {
279 <            Object[] oldData = elementData;
280 <            int newCapacity = (capacityIncrement > 0) ?
281 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
282 <            if (newCapacity < minCapacity) {
283 <                newCapacity = minCapacity;
284 <            }
285 <            elementData = Arrays.copyOf(elementData, newCapacity);
286 <        }
269 >     * Returns a capacity at least as large as the given minimum capacity.
270 >     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
271 >     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
272 >     *
273 >     * @param minCapacity the desired minimum capacity
274 >     * @throws OutOfMemoryError if minCapacity is less than zero
275 >     */
276 >    private int newCapacity(int minCapacity) {
277 >        // overflow-conscious code
278 >        int oldCapacity = elementData.length;
279 >        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
280 >                                         capacityIncrement : oldCapacity);
281 >        if (newCapacity - minCapacity <= 0) {
282 >            if (minCapacity < 0) // overflow
283 >                throw new OutOfMemoryError();
284 >            return minCapacity;
285 >        }
286 >        return (newCapacity - MAX_ARRAY_SIZE <= 0)
287 >            ? newCapacity
288 >            : hugeCapacity(minCapacity);
289 >    }
290 >
291 >    private static int hugeCapacity(int minCapacity) {
292 >        if (minCapacity < 0) // overflow
293 >            throw new OutOfMemoryError();
294 >        return (minCapacity > MAX_ARRAY_SIZE) ?
295 >            Integer.MAX_VALUE :
296 >            MAX_ARRAY_SIZE;
297      }
298  
299      /**
# Line 237 | Line 306 | public class Vector<E>
306       * @throws ArrayIndexOutOfBoundsException if the new size is negative
307       */
308      public synchronized void setSize(int newSize) {
309 <        modCount++;
310 <        if (newSize > elementCount) {
311 <            ensureCapacityHelper(newSize);
312 <        } else {
313 <            for (int i = newSize ; i < elementCount ; i++) {
314 <                elementData[i] = null;
315 <            }
247 <        }
248 <        elementCount = newSize;
309 >        modCount++;
310 >        if (newSize > elementData.length)
311 >            grow(newSize);
312 >        final Object[] es = elementData;
313 >        for (int to = elementCount, i = newSize; i < to; i++)
314 >            es[i] = null;
315 >        elementCount = newSize;
316      }
317  
318      /**
# Line 256 | Line 323 | public class Vector<E>
323       *          of this vector)
324       */
325      public synchronized int capacity() {
326 <        return elementData.length;
326 >        return elementData.length;
327      }
328  
329      /**
# Line 265 | Line 332 | public class Vector<E>
332       * @return  the number of components in this vector
333       */
334      public synchronized int size() {
335 <        return elementCount;
335 >        return elementCount;
336      }
337  
338      /**
# Line 276 | Line 343 | public class Vector<E>
343       *          {@code false} otherwise.
344       */
345      public synchronized boolean isEmpty() {
346 <        return elementCount == 0;
346 >        return elementCount == 0;
347      }
348  
349      /**
350       * Returns an enumeration of the components of this vector. The
351       * returned {@code Enumeration} object will generate all items in
352       * this vector. The first item generated is the item at index {@code 0},
353 <     * then the item at index {@code 1}, and so on.
353 >     * then the item at index {@code 1}, and so on. If the vector is
354 >     * structurally modified while enumerating over the elements then the
355 >     * results of enumerating are undefined.
356       *
357       * @return  an enumeration of the components of this vector
358       * @see     Iterator
359       */
360      public Enumeration<E> elements() {
361 <        return new Enumeration<E>() {
362 <            int count = 0;
361 >        return new Enumeration<E>() {
362 >            int count = 0;
363 >
364 >            public boolean hasMoreElements() {
365 >                return count < elementCount;
366 >            }
367  
368 <            public boolean hasMoreElements() {
369 <                return count < elementCount;
370 <            }
371 <
372 <            public E nextElement() {
373 <                synchronized (Vector.this) {
374 <                    if (count < elementCount) {
375 <                        return (E)elementData[count++];
376 <                    }
304 <                }
305 <                throw new NoSuchElementException("Vector Enumeration");
306 <            }
307 <        };
368 >            public E nextElement() {
369 >                synchronized (Vector.this) {
370 >                    if (count < elementCount) {
371 >                        return elementData(count++);
372 >                    }
373 >                }
374 >                throw new NoSuchElementException("Vector Enumeration");
375 >            }
376 >        };
377      }
378  
379      /**
380       * Returns {@code true} if this vector contains the specified element.
381       * More formally, returns {@code true} if and only if this vector
382       * contains at least one element {@code e} such that
383 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
383 >     * {@code Objects.equals(o, e)}.
384       *
385       * @param o element whose presence in this vector is to be tested
386       * @return {@code true} if this vector contains the specified element
387       */
388      public boolean contains(Object o) {
389 <        return indexOf(o, 0) >= 0;
389 >        return indexOf(o, 0) >= 0;
390      }
391  
392      /**
393       * Returns the index of the first occurrence of the specified element
394       * in this vector, or -1 if this vector does not contain the element.
395       * More formally, returns the lowest index {@code i} such that
396 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
396 >     * {@code Objects.equals(o, get(i))},
397       * or -1 if there is no such index.
398       *
399       * @param o element to search for
# Line 332 | Line 401 | public class Vector<E>
401       *         this vector, or -1 if this vector does not contain the element
402       */
403      public int indexOf(Object o) {
404 <        return indexOf(o, 0);
404 >        return indexOf(o, 0);
405      }
406  
407      /**
# Line 340 | Line 409 | public class Vector<E>
409       * this vector, searching forwards from {@code index}, or returns -1 if
410       * the element is not found.
411       * More formally, returns the lowest index {@code i} such that
412 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
412 >     * {@code (i >= index && Objects.equals(o, get(i)))},
413       * or -1 if there is no such index.
414       *
415       * @param o element to search for
# Line 352 | Line 421 | public class Vector<E>
421       * @see     Object#equals(Object)
422       */
423      public synchronized int indexOf(Object o, int index) {
424 <        if (o == null) {
425 <            for (int i = index ; i < elementCount ; i++)
426 <                if (elementData[i]==null)
427 <                    return i;
428 <        } else {
429 <            for (int i = index ; i < elementCount ; i++)
430 <                if (o.equals(elementData[i]))
431 <                    return i;
432 <        }
433 <        return -1;
424 >        if (o == null) {
425 >            for (int i = index ; i < elementCount ; i++)
426 >                if (elementData[i]==null)
427 >                    return i;
428 >        } else {
429 >            for (int i = index ; i < elementCount ; i++)
430 >                if (o.equals(elementData[i]))
431 >                    return i;
432 >        }
433 >        return -1;
434      }
435  
436      /**
437       * Returns the index of the last occurrence of the specified element
438       * in this vector, or -1 if this vector does not contain the element.
439       * More formally, returns the highest index {@code i} such that
440 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
440 >     * {@code Objects.equals(o, get(i))},
441       * or -1 if there is no such index.
442       *
443       * @param o element to search for
# Line 376 | Line 445 | public class Vector<E>
445       *         this vector, or -1 if this vector does not contain the element
446       */
447      public synchronized int lastIndexOf(Object o) {
448 <        return lastIndexOf(o, elementCount-1);
448 >        return lastIndexOf(o, elementCount-1);
449      }
450  
451      /**
# Line 384 | Line 453 | public class Vector<E>
453       * this vector, searching backwards from {@code index}, or returns -1 if
454       * the element is not found.
455       * More formally, returns the highest index {@code i} such that
456 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
456 >     * {@code (i <= index && Objects.equals(o, get(i)))},
457       * or -1 if there is no such index.
458       *
459       * @param o element to search for
# Line 399 | Line 468 | public class Vector<E>
468          if (index >= elementCount)
469              throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
470  
471 <        if (o == null) {
472 <            for (int i = index; i >= 0; i--)
473 <                if (elementData[i]==null)
474 <                    return i;
475 <        } else {
476 <            for (int i = index; i >= 0; i--)
477 <                if (o.equals(elementData[i]))
478 <                    return i;
479 <        }
480 <        return -1;
471 >        if (o == null) {
472 >            for (int i = index; i >= 0; i--)
473 >                if (elementData[i]==null)
474 >                    return i;
475 >        } else {
476 >            for (int i = index; i >= 0; i--)
477 >                if (o.equals(elementData[i]))
478 >                    return i;
479 >        }
480 >        return -1;
481      }
482  
483      /**
# Line 420 | Line 489 | public class Vector<E>
489       * @param      index   an index into this vector
490       * @return     the component at the specified index
491       * @throws ArrayIndexOutOfBoundsException if the index is out of range
492 <     *         ({@code index < 0 || index >= size()})
492 >     *         ({@code index < 0 || index >= size()})
493       */
494      public synchronized E elementAt(int index) {
495 <        if (index >= elementCount) {
496 <            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
497 <        }
495 >        if (index >= elementCount) {
496 >            throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
497 >        }
498  
499 <        return (E)elementData[index];
499 >        return elementData(index);
500      }
501  
502      /**
# Line 438 | Line 507 | public class Vector<E>
507       * @throws NoSuchElementException if this vector has no components
508       */
509      public synchronized E firstElement() {
510 <        if (elementCount == 0) {
511 <            throw new NoSuchElementException();
512 <        }
513 <        return (E)elementData[0];
510 >        if (elementCount == 0) {
511 >            throw new NoSuchElementException();
512 >        }
513 >        return elementData(0);
514      }
515  
516      /**
517       * Returns the last component of the vector.
518       *
519       * @return  the last component of the vector, i.e., the component at index
520 <     *          <code>size()&nbsp;-&nbsp;1</code>.
520 >     *          {@code size() - 1}
521       * @throws NoSuchElementException if this vector is empty
522       */
523      public synchronized E lastElement() {
524 <        if (elementCount == 0) {
525 <            throw new NoSuchElementException();
526 <        }
527 <        return (E)elementData[elementCount - 1];
524 >        if (elementCount == 0) {
525 >            throw new NoSuchElementException();
526 >        }
527 >        return elementData(elementCount - 1);
528      }
529  
530      /**
# Line 476 | Line 545 | public class Vector<E>
545       * @param      obj     what the component is to be set to
546       * @param      index   the specified index
547       * @throws ArrayIndexOutOfBoundsException if the index is out of range
548 <     *         ({@code index < 0 || index >= size()})
548 >     *         ({@code index < 0 || index >= size()})
549       */
550      public synchronized void setElementAt(E obj, int index) {
551 <        if (index >= elementCount) {
552 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
553 <                                                     elementCount);
554 <        }
555 <        elementData[index] = obj;
551 >        if (index >= elementCount) {
552 >            throw new ArrayIndexOutOfBoundsException(index + " >= " +
553 >                                                     elementCount);
554 >        }
555 >        elementData[index] = obj;
556      }
557  
558      /**
# Line 503 | Line 572 | public class Vector<E>
572       *
573       * @param      index   the index of the object to remove
574       * @throws ArrayIndexOutOfBoundsException if the index is out of range
575 <     *         ({@code index < 0 || index >= size()})
575 >     *         ({@code index < 0 || index >= size()})
576       */
577      public synchronized void removeElementAt(int index) {
578 <        modCount++;
579 <        if (index >= elementCount) {
580 <            throw new ArrayIndexOutOfBoundsException(index + " >= " +
581 <                                                     elementCount);
582 <        }
583 <        else if (index < 0) {
584 <            throw new ArrayIndexOutOfBoundsException(index);
585 <        }
586 <        int j = elementCount - index - 1;
587 <        if (j > 0) {
588 <            System.arraycopy(elementData, index + 1, elementData, index, j);
589 <        }
590 <        elementCount--;
591 <        elementData[elementCount] = null; /* to let gc do its work */
578 >        if (index >= elementCount) {
579 >            throw new ArrayIndexOutOfBoundsException(index + " >= " +
580 >                                                     elementCount);
581 >        }
582 >        else if (index < 0) {
583 >            throw new ArrayIndexOutOfBoundsException(index);
584 >        }
585 >        int j = elementCount - index - 1;
586 >        if (j > 0) {
587 >            System.arraycopy(elementData, index + 1, elementData, index, j);
588 >        }
589 >        modCount++;
590 >        elementCount--;
591 >        elementData[elementCount] = null; /* to let gc do its work */
592 >        // checkInvariants();
593      }
594  
595      /**
# Line 543 | Line 613 | public class Vector<E>
613       * @param      obj     the component to insert
614       * @param      index   where to insert the new component
615       * @throws ArrayIndexOutOfBoundsException if the index is out of range
616 <     *         ({@code index < 0 || index > size()})
616 >     *         ({@code index < 0 || index > size()})
617       */
618      public synchronized void insertElementAt(E obj, int index) {
619 <        modCount++;
620 <        if (index > elementCount) {
621 <            throw new ArrayIndexOutOfBoundsException(index
622 <                                                     + " > " + elementCount);
623 <        }
624 <        ensureCapacityHelper(elementCount + 1);
625 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
626 <        elementData[index] = obj;
627 <        elementCount++;
619 >        if (index > elementCount) {
620 >            throw new ArrayIndexOutOfBoundsException(index
621 >                                                     + " > " + elementCount);
622 >        }
623 >        modCount++;
624 >        final int s = elementCount;
625 >        Object[] elementData = this.elementData;
626 >        if (s == elementData.length)
627 >            elementData = grow();
628 >        System.arraycopy(elementData, index,
629 >                         elementData, index + 1,
630 >                         s - index);
631 >        elementData[index] = obj;
632 >        elementCount = s + 1;
633      }
634  
635      /**
# Line 569 | Line 644 | public class Vector<E>
644       * @param   obj   the component to be added
645       */
646      public synchronized void addElement(E obj) {
647 <        modCount++;
648 <        ensureCapacityHelper(elementCount + 1);
574 <        elementData[elementCount++] = obj;
647 >        modCount++;
648 >        add(obj, elementData, elementCount);
649      }
650  
651      /**
# Line 590 | Line 664 | public class Vector<E>
664       *          vector; {@code false} otherwise.
665       */
666      public synchronized boolean removeElement(Object obj) {
667 <        modCount++;
668 <        int i = indexOf(obj);
669 <        if (i >= 0) {
670 <            removeElementAt(i);
671 <            return true;
672 <        }
673 <        return false;
667 >        modCount++;
668 >        int i = indexOf(obj);
669 >        if (i >= 0) {
670 >            removeElementAt(i);
671 >            return true;
672 >        }
673 >        return false;
674      }
675  
676      /**
# Line 606 | Line 680 | public class Vector<E>
680       * method (which is part of the {@link List} interface).
681       */
682      public synchronized void removeAllElements() {
683 +        final Object[] es = elementData;
684 +        for (int to = elementCount, i = elementCount = 0; i < to; i++)
685 +            es[i] = null;
686          modCount++;
610        // Let gc do its work
611        for (int i = 0; i < elementCount; i++)
612            elementData[i] = null;
613
614        elementCount = 0;
687      }
688  
689      /**
# Line 622 | Line 694 | public class Vector<E>
694       * @return  a clone of this vector
695       */
696      public synchronized Object clone() {
697 <        try {
698 <            Vector<E> v = (Vector<E>) super.clone();
699 <            v.elementData = Arrays.copyOf(elementData, elementCount);
700 <            v.modCount = 0;
701 <            return v;
702 <        } catch (CloneNotSupportedException e) {
703 <            // this shouldn't happen, since we are Cloneable
704 <            throw new InternalError();
705 <        }
697 >        try {
698 >            @SuppressWarnings("unchecked")
699 >            Vector<E> v = (Vector<E>) super.clone();
700 >            v.elementData = Arrays.copyOf(elementData, elementCount);
701 >            v.modCount = 0;
702 >            return v;
703 >        } catch (CloneNotSupportedException e) {
704 >            // this shouldn't happen, since we are Cloneable
705 >            throw new InternalError(e);
706 >        }
707      }
708  
709      /**
# Line 657 | Line 730 | public class Vector<E>
730       * of the Vector <em>only</em> if the caller knows that the Vector
731       * does not contain any null elements.)
732       *
733 +     * @param <T> type of array elements. The same type as {@code <E>} or a
734 +     * supertype of {@code <E>}.
735       * @param a the array into which the elements of the Vector are to
736 <     *          be stored, if it is big enough; otherwise, a new array of the
737 <     *          same runtime type is allocated for this purpose.
736 >     *          be stored, if it is big enough; otherwise, a new array of the
737 >     *          same runtime type is allocated for this purpose.
738       * @return an array containing the elements of the Vector
739 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
740 <     * of the runtime type of every element in this Vector
739 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
740 >     * a supertype of the runtime type, {@code <E>}, of every element in this
741 >     * Vector
742       * @throws NullPointerException if the given array is null
743       * @since 1.2
744       */
745 +    @SuppressWarnings("unchecked")
746      public synchronized <T> T[] toArray(T[] a) {
747          if (a.length < elementCount)
748              return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
749  
750 <        System.arraycopy(elementData, 0, a, 0, elementCount);
750 >        System.arraycopy(elementData, 0, a, 0, elementCount);
751  
752          if (a.length > elementCount)
753              a[elementCount] = null;
# Line 680 | Line 757 | public class Vector<E>
757  
758      // Positional Access Operations
759  
760 +    @SuppressWarnings("unchecked")
761 +    E elementData(int index) {
762 +        return (E) elementData[index];
763 +    }
764 +
765 +    @SuppressWarnings("unchecked")
766 +    static <E> E elementAt(Object[] es, int index) {
767 +        return (E) es[index];
768 +    }
769 +
770      /**
771       * Returns the element at the specified position in this Vector.
772       *
# Line 690 | Line 777 | public class Vector<E>
777       * @since 1.2
778       */
779      public synchronized E get(int index) {
780 <        if (index >= elementCount)
781 <            throw new ArrayIndexOutOfBoundsException(index);
780 >        if (index >= elementCount)
781 >            throw new ArrayIndexOutOfBoundsException(index);
782  
783 <        return (E)elementData[index];
783 >        return elementData(index);
784      }
785  
786      /**
# Line 704 | Line 791 | public class Vector<E>
791       * @param element element to be stored at the specified position
792       * @return the element previously at the specified position
793       * @throws ArrayIndexOutOfBoundsException if the index is out of range
794 <     *         ({@code index < 0 || index >= size()})
794 >     *         ({@code index < 0 || index >= size()})
795       * @since 1.2
796       */
797      public synchronized E set(int index, E element) {
798 <        if (index >= elementCount)
799 <            throw new ArrayIndexOutOfBoundsException(index);
798 >        if (index >= elementCount)
799 >            throw new ArrayIndexOutOfBoundsException(index);
800 >
801 >        E oldValue = elementData(index);
802 >        elementData[index] = element;
803 >        return oldValue;
804 >    }
805  
806 <        Object oldValue = elementData[index];
807 <        elementData[index] = element;
808 <        return (E)oldValue;
806 >    /**
807 >     * This helper method split out from add(E) to keep method
808 >     * bytecode size under 35 (the -XX:MaxInlineSize default value),
809 >     * which helps when add(E) is called in a C1-compiled loop.
810 >     */
811 >    private void add(E e, Object[] elementData, int s) {
812 >        if (s == elementData.length)
813 >            elementData = grow();
814 >        elementData[s] = e;
815 >        elementCount = s + 1;
816 >        // checkInvariants();
817      }
818  
819      /**
# Line 724 | Line 824 | public class Vector<E>
824       * @since 1.2
825       */
826      public synchronized boolean add(E e) {
827 <        modCount++;
828 <        ensureCapacityHelper(elementCount + 1);
729 <        elementData[elementCount++] = e;
827 >        modCount++;
828 >        add(e, elementData, elementCount);
829          return true;
830      }
831  
# Line 734 | Line 833 | public class Vector<E>
833       * Removes the first occurrence of the specified element in this Vector
834       * If the Vector does not contain the element, it is unchanged.  More
835       * formally, removes the element with the lowest index i such that
836 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
836 >     * {@code Objects.equals(o, get(i))} (if such
837       * an element exists).
838       *
839       * @param o element to be removed from this Vector, if present
# Line 765 | Line 864 | public class Vector<E>
864       * Shifts any subsequent elements to the left (subtracts one from their
865       * indices).  Returns the element that was removed from the Vector.
866       *
768     * @throws ArrayIndexOutOfBoundsException if the index is out of range
769     *         ({@code index < 0 || index >= size()})
867       * @param index the index of the element to be removed
868       * @return element that was removed
869 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
870 +     *         ({@code index < 0 || index >= size()})
871       * @since 1.2
872       */
873      public synchronized E remove(int index) {
874 <        modCount++;
875 <        if (index >= elementCount)
876 <            throw new ArrayIndexOutOfBoundsException(index);
877 <        Object oldValue = elementData[index];
878 <
879 <        int numMoved = elementCount - index - 1;
880 <        if (numMoved > 0)
881 <            System.arraycopy(elementData, index+1, elementData, index,
882 <                             numMoved);
883 <        elementData[--elementCount] = null; // Let gc do its work
874 >        modCount++;
875 >        if (index >= elementCount)
876 >            throw new ArrayIndexOutOfBoundsException(index);
877 >        E oldValue = elementData(index);
878 >
879 >        int numMoved = elementCount - index - 1;
880 >        if (numMoved > 0)
881 >            System.arraycopy(elementData, index+1, elementData, index,
882 >                             numMoved);
883 >        elementData[--elementCount] = null; // Let gc do its work
884  
885 <        return (E)oldValue;
885 >        // checkInvariants();
886 >        return oldValue;
887      }
888  
889      /**
# Line 805 | Line 905 | public class Vector<E>
905       * @param   c a collection whose elements will be tested for containment
906       *          in this Vector
907       * @return true if this Vector contains all of the elements in the
908 <     *         specified collection
908 >     *         specified collection
909       * @throws NullPointerException if the specified collection is null
910       */
911      public synchronized boolean containsAll(Collection<?> c) {
# Line 825 | Line 925 | public class Vector<E>
925       * @throws NullPointerException if the specified collection is null
926       * @since 1.2
927       */
928 <    public synchronized boolean addAll(Collection<? extends E> c) {
829 <        modCount++;
928 >    public boolean addAll(Collection<? extends E> c) {
929          Object[] a = c.toArray();
930 +        modCount++;
931          int numNew = a.length;
932 <        ensureCapacityHelper(elementCount + numNew);
933 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
934 <        elementCount += numNew;
935 <        return numNew != 0;
932 >        if (numNew == 0)
933 >            return false;
934 >        synchronized (this) {
935 >            Object[] elementData = this.elementData;
936 >            final int s = elementCount;
937 >            if (numNew > elementData.length - s)
938 >                elementData = grow(s + numNew);
939 >            System.arraycopy(a, 0, elementData, s, numNew);
940 >            elementCount = s + numNew;
941 >            // checkInvariants();
942 >            return true;
943 >        }
944      }
945  
946      /**
# Line 843 | Line 951 | public class Vector<E>
951       * @return true if this Vector changed as a result of the call
952       * @throws ClassCastException if the types of one or more elements
953       *         in this vector are incompatible with the specified
954 <     *         collection (optional)
954 >     *         collection
955 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
956       * @throws NullPointerException if this vector contains one or more null
957       *         elements and the specified collection does not support null
958 <     *         elements (optional), or if the specified collection is null
958 >     *         elements
959 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
960 >     *         or if the specified collection is null
961       * @since 1.2
962       */
963 <    public synchronized boolean removeAll(Collection<?> c) {
964 <        return super.removeAll(c);
963 >    public boolean removeAll(Collection<?> c) {
964 >        Objects.requireNonNull(c);
965 >        return bulkRemove(e -> c.contains(e));
966      }
967  
968      /**
# Line 863 | Line 975 | public class Vector<E>
975       * @return true if this Vector changed as a result of the call
976       * @throws ClassCastException if the types of one or more elements
977       *         in this vector are incompatible with the specified
978 <     *         collection (optional)
978 >     *         collection
979 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
980       * @throws NullPointerException if this vector contains one or more null
981       *         elements and the specified collection does not support null
982 <     *         elements (optional), or if the specified collection is null
982 >     *         elements
983 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
984 >     *         or if the specified collection is null
985       * @since 1.2
986       */
987 <    public synchronized boolean retainAll(Collection<?> c)  {
988 <        return super.retainAll(c);
987 >    public boolean retainAll(Collection<?> c) {
988 >        Objects.requireNonNull(c);
989 >        return bulkRemove(e -> !c.contains(e));
990 >    }
991 >
992 >    /**
993 >     * @throws NullPointerException {@inheritDoc}
994 >     */
995 >    @Override
996 >    public boolean removeIf(Predicate<? super E> filter) {
997 >        Objects.requireNonNull(filter);
998 >        return bulkRemove(filter);
999 >    }
1000 >
1001 >    // A tiny bit set implementation
1002 >
1003 >    private static long[] nBits(int n) {
1004 >        return new long[((n - 1) >> 6) + 1];
1005 >    }
1006 >    private static void setBit(long[] bits, int i) {
1007 >        bits[i >> 6] |= 1L << i;
1008 >    }
1009 >    private static boolean isClear(long[] bits, int i) {
1010 >        return (bits[i >> 6] & (1L << i)) == 0;
1011 >    }
1012 >
1013 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
1014 >        int expectedModCount = modCount;
1015 >        final Object[] es = elementData;
1016 >        final int end = elementCount;
1017 >        int i;
1018 >        // Optimize for initial run of survivors
1019 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
1020 >            ;
1021 >        // Tolerate predicates that reentrantly access the collection for
1022 >        // read (but writers still get CME), so traverse once to find
1023 >        // elements to delete, a second pass to physically expunge.
1024 >        if (i < end) {
1025 >            final int beg = i;
1026 >            final long[] deathRow = nBits(end - beg);
1027 >            deathRow[0] = 1L;   // set bit 0
1028 >            for (i = beg + 1; i < end; i++)
1029 >                if (filter.test(elementAt(es, i)))
1030 >                    setBit(deathRow, i - beg);
1031 >            if (modCount != expectedModCount)
1032 >                throw new ConcurrentModificationException();
1033 >            modCount++;
1034 >            int w = beg;
1035 >            for (i = beg; i < end; i++)
1036 >                if (isClear(deathRow, i - beg))
1037 >                    es[w++] = es[i];
1038 >            for (i = elementCount = w; i < end; i++)
1039 >                es[i] = null;
1040 >            // checkInvariants();
1041 >            return true;
1042 >        } else {
1043 >            if (modCount != expectedModCount)
1044 >                throw new ConcurrentModificationException();
1045 >            // checkInvariants();
1046 >            return false;
1047 >        }
1048      }
1049  
1050      /**
# Line 891 | Line 1065 | public class Vector<E>
1065       * @since 1.2
1066       */
1067      public synchronized boolean addAll(int index, Collection<? extends E> c) {
1068 <        modCount++;
1069 <        if (index < 0 || index > elementCount)
896 <            throw new ArrayIndexOutOfBoundsException(index);
1068 >        if (index < 0 || index > elementCount)
1069 >            throw new ArrayIndexOutOfBoundsException(index);
1070  
1071          Object[] a = c.toArray();
1072 <        int numNew = a.length;
1073 <        ensureCapacityHelper(elementCount + numNew);
1074 <
1075 <        int numMoved = elementCount - index;
1076 <        if (numMoved > 0)
1077 <            System.arraycopy(elementData, index, elementData, index + numNew,
1078 <                             numMoved);
1079 <
1072 >        modCount++;
1073 >        int numNew = a.length;
1074 >        if (numNew == 0)
1075 >            return false;
1076 >        Object[] elementData = this.elementData;
1077 >        final int s = elementCount;
1078 >        if (numNew > elementData.length - s)
1079 >            elementData = grow(s + numNew);
1080 >
1081 >        int numMoved = s - index;
1082 >        if (numMoved > 0)
1083 >            System.arraycopy(elementData, index,
1084 >                             elementData, index + numNew,
1085 >                             numMoved);
1086          System.arraycopy(a, 0, elementData, index, numNew);
1087 <        elementCount += numNew;
1088 <        return numNew != 0;
1087 >        elementCount = s + numNew;
1088 >        // checkInvariants();
1089 >        return true;
1090      }
1091  
1092      /**
# Line 914 | Line 1094 | public class Vector<E>
1094       * true if and only if the specified Object is also a List, both Lists
1095       * have the same size, and all corresponding pairs of elements in the two
1096       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1097 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1098 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1097 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1098 >     * In other words, two Lists are defined to be
1099       * equal if they contain the same elements in the same order.
1100       *
1101       * @param o the Object to be compared for equality with this Vector
# Line 941 | Line 1121 | public class Vector<E>
1121      }
1122  
1123      /**
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 performs 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    /**
1124       * Returns a view of the portion of this List between fromIndex,
1125       * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1126       * equal, the returned List is empty.)  The returned List is backed by this
# Line 1141 | Line 1129 | public class Vector<E>
1129       * operations supported by this List.
1130       *
1131       * <p>This method eliminates the need for explicit range operations (of
1132 <     * the sort that commonly exist for arrays).   Any operation that expects
1132 >     * the sort that commonly exist for arrays).  Any operation that expects
1133       * a List can be used as a range operation by operating on a subList view
1134       * instead of a whole List.  For example, the following idiom
1135       * removes a range of elements from a List:
1136       * <pre>
1137 <     *      list.subList(from, to).clear();
1137 >     *      list.subList(from, to).clear();
1138       * </pre>
1139       * Similar idioms may be constructed for indexOf and lastIndexOf,
1140       * and all of the algorithms in the Collections class can be applied to
# Line 1164 | Line 1152 | public class Vector<E>
1152       * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1153       *         {@code (fromIndex < 0 || toIndex > size)}
1154       * @throws IllegalArgumentException if the endpoint indices are out of order
1155 <     *         {@code (fromIndex > toIndex)}
1155 >     *         {@code (fromIndex > toIndex)}
1156       */
1157      public synchronized List<E> subList(int fromIndex, int toIndex) {
1158 <        return new VectorSubList(this, this, fromIndex, fromIndex, toIndex);
1158 >        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1159 >                                            this);
1160      }
1161  
1162      /**
1163 <     * This class specializes the AbstractList version of SubList to
1164 <     * avoid the double-indirection penalty that would arise using a
1165 <     * synchronized wrapper, as well as to avoid some unnecessary
1166 <     * checks in sublist iterators.
1167 <     */
1168 <    private static final class VectorSubList<E> extends AbstractList<E> implements RandomAccess {
1169 <        final Vector<E> base;             // base list
1170 <        final AbstractList<E> parent;     // Creating list
1171 <        final int baseOffset;             // index wrt Vector
1172 <        final int parentOffset;           // index wrt parent
1173 <        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 <        }
1163 >     * Removes from this list all of the elements whose index is between
1164 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1165 >     * Shifts any succeeding elements to the left (reduces their index).
1166 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1167 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
1168 >     */
1169 >    protected synchronized void removeRange(int fromIndex, int toIndex) {
1170 >        modCount++;
1171 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1172 >        // checkInvariants();
1173 >    }
1174  
1175 <        public E get(int index) {
1176 <            synchronized(base) {
1177 <                if (index < 0 || index >= length)
1178 <                    throw indexError(index);
1179 <                if (base.modCount != modCount)
1180 <                    throw new ConcurrentModificationException();
1228 <                return base.get(index + baseOffset);
1229 <            }
1230 <        }
1175 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1176 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1177 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1178 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1179 >            es[i] = null;
1180 >    }
1181  
1182 <        public int size() {
1183 <            synchronized(base) {
1184 <                if (base.modCount != modCount)
1185 <                    throw new ConcurrentModificationException();
1186 <                return length;
1187 <            }
1182 >    /**
1183 >     * Loads a {@code Vector} instance from a stream
1184 >     * (that is, deserializes it).
1185 >     * This method performs checks to ensure the consistency
1186 >     * of the fields.
1187 >     *
1188 >     * @param in the stream
1189 >     * @throws java.io.IOException if an I/O error occurs
1190 >     * @throws ClassNotFoundException if the stream contains data
1191 >     *         of a non-existing class
1192 >     */
1193 >    private void readObject(ObjectInputStream in)
1194 >            throws IOException, ClassNotFoundException {
1195 >        ObjectInputStream.GetField gfields = in.readFields();
1196 >        int count = gfields.get("elementCount", 0);
1197 >        Object[] data = (Object[])gfields.get("elementData", null);
1198 >        if (count < 0 || data == null || count > data.length) {
1199 >            throw new StreamCorruptedException("Inconsistent vector internals");
1200          }
1201 +        elementCount = count;
1202 +        elementData = data.clone();
1203 +    }
1204  
1205 <        public void add(int index, E element) {
1206 <            synchronized(base) {
1207 <                if (index < 0 || index > length)
1208 <                    throw indexError(index);
1209 <                if (base.modCount != modCount)
1210 <                    throw new ConcurrentModificationException();
1211 <                parent.add(index + parentOffset, element);
1212 <                length++;
1213 <                modCount = base.modCount;
1214 <            }
1205 >    /**
1206 >     * Saves the state of the {@code Vector} instance to a stream
1207 >     * (that is, serializes it).
1208 >     * This method performs synchronization to ensure the consistency
1209 >     * of the serialized data.
1210 >     *
1211 >     * @param s the stream
1212 >     * @throws java.io.IOException if an I/O error occurs
1213 >     */
1214 >    private void writeObject(java.io.ObjectOutputStream s)
1215 >            throws java.io.IOException {
1216 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1217 >        final Object[] data;
1218 >        synchronized (this) {
1219 >            fields.put("capacityIncrement", capacityIncrement);
1220 >            fields.put("elementCount", elementCount);
1221 >            data = elementData.clone();
1222          }
1223 +        fields.put("elementData", data);
1224 +        s.writeFields();
1225 +    }
1226  
1227 <        public E remove(int index) {
1228 <            synchronized(base) {
1229 <                if (index < 0 || index >= length)
1230 <                    throw indexError(index);
1231 <                if (base.modCount != modCount)
1232 <                    throw new ConcurrentModificationException();
1233 <                E result = parent.remove(index + parentOffset);
1234 <                length--;
1235 <                modCount = base.modCount;
1236 <                return result;
1237 <            }
1227 >    /**
1228 >     * Returns a list iterator over the elements in this list (in proper
1229 >     * sequence), starting at the specified position in the list.
1230 >     * The specified index indicates the first element that would be
1231 >     * returned by an initial call to {@link ListIterator#next next}.
1232 >     * An initial call to {@link ListIterator#previous previous} would
1233 >     * return the element with the specified index minus one.
1234 >     *
1235 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1236 >     *
1237 >     * @throws IndexOutOfBoundsException {@inheritDoc}
1238 >     */
1239 >    public synchronized ListIterator<E> listIterator(int index) {
1240 >        if (index < 0 || index > elementCount)
1241 >            throw new IndexOutOfBoundsException("Index: "+index);
1242 >        return new ListItr(index);
1243 >    }
1244 >
1245 >    /**
1246 >     * Returns a list iterator over the elements in this list (in proper
1247 >     * sequence).
1248 >     *
1249 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1250 >     *
1251 >     * @see #listIterator(int)
1252 >     */
1253 >    public synchronized ListIterator<E> listIterator() {
1254 >        return new ListItr(0);
1255 >    }
1256 >
1257 >    /**
1258 >     * Returns an iterator over the elements in this list in proper sequence.
1259 >     *
1260 >     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1261 >     *
1262 >     * @return an iterator over the elements in this list in proper sequence
1263 >     */
1264 >    public synchronized Iterator<E> iterator() {
1265 >        return new Itr();
1266 >    }
1267 >
1268 >    /**
1269 >     * An optimized version of AbstractList.Itr
1270 >     */
1271 >    private class Itr implements Iterator<E> {
1272 >        int cursor;       // index of next element to return
1273 >        int lastRet = -1; // index of last element returned; -1 if no such
1274 >        int expectedModCount = modCount;
1275 >
1276 >        public boolean hasNext() {
1277 >            // Racy but within spec, since modifications are checked
1278 >            // within or after synchronization in next/previous
1279 >            return cursor != elementCount;
1280          }
1281  
1282 <        protected void removeRange(int fromIndex, int toIndex) {
1283 <            synchronized(base) {
1284 <                if (base.modCount != modCount)
1285 <                    throw new ConcurrentModificationException();
1286 <                parent.removeRange(fromIndex + parentOffset,
1287 <                                   toIndex + parentOffset);
1288 <                length -= (toIndex-fromIndex);
1289 <                modCount = base.modCount;
1282 >        public E next() {
1283 >            synchronized (Vector.this) {
1284 >                checkForComodification();
1285 >                int i = cursor;
1286 >                if (i >= elementCount)
1287 >                    throw new NoSuchElementException();
1288 >                cursor = i + 1;
1289 >                return elementData(lastRet = i);
1290              }
1291          }
1292  
1293 <        public boolean addAll(Collection<? extends E> c) {
1294 <            return addAll(length, c);
1293 >        public void remove() {
1294 >            if (lastRet == -1)
1295 >                throw new IllegalStateException();
1296 >            synchronized (Vector.this) {
1297 >                checkForComodification();
1298 >                Vector.this.remove(lastRet);
1299 >                expectedModCount = modCount;
1300 >            }
1301 >            cursor = lastRet;
1302 >            lastRet = -1;
1303          }
1304  
1305 <        public boolean addAll(int index, Collection<? extends E> c) {
1306 <            synchronized(base) {
1307 <                if (index < 0 || index > length)
1308 <                    throw indexError(index);
1309 <                int cSize = c.size();
1310 <                if (cSize==0)
1311 <                    return false;
1312 <
1313 <                if (base.modCount != modCount)
1305 >        @Override
1306 >        public void forEachRemaining(Consumer<? super E> action) {
1307 >            Objects.requireNonNull(action);
1308 >            synchronized (Vector.this) {
1309 >                final int size = elementCount;
1310 >                int i = cursor;
1311 >                if (i >= size) {
1312 >                    return;
1313 >                }
1314 >                final Object[] es = elementData;
1315 >                if (i >= es.length)
1316                      throw new ConcurrentModificationException();
1317 <                parent.addAll(parentOffset + index, c);
1318 <                modCount = base.modCount;
1319 <                length += cSize;
1320 <                return true;
1317 >                while (i < size && modCount == expectedModCount)
1318 >                    action.accept(elementAt(es, i++));
1319 >                // update once at end of iteration to reduce heap write traffic
1320 >                cursor = i;
1321 >                lastRet = i - 1;
1322 >                checkForComodification();
1323              }
1324          }
1325  
1326 <        public boolean equals(Object o) {
1327 <            synchronized(base) {return super.equals(o);}
1326 >        final void checkForComodification() {
1327 >            if (modCount != expectedModCount)
1328 >                throw new ConcurrentModificationException();
1329          }
1330 +    }
1331  
1332 <        public int hashCode() {
1333 <            synchronized(base) {return super.hashCode();}
1332 >    /**
1333 >     * An optimized version of AbstractList.ListItr
1334 >     */
1335 >    final class ListItr extends Itr implements ListIterator<E> {
1336 >        ListItr(int index) {
1337 >            super();
1338 >            cursor = index;
1339          }
1340  
1341 <        public int indexOf(Object o) {
1342 <            synchronized(base) {return super.indexOf(o);}
1341 >        public boolean hasPrevious() {
1342 >            return cursor != 0;
1343          }
1344  
1345 <        public int lastIndexOf(Object o) {
1346 <            synchronized(base) {return super.lastIndexOf(o);}
1345 >        public int nextIndex() {
1346 >            return cursor;
1347          }
1348  
1349 <        public List<E> subList(int fromIndex, int toIndex) {
1350 <            return new VectorSubList(base, this, fromIndex + baseOffset,
1315 <                                     fromIndex, toIndex);
1349 >        public int previousIndex() {
1350 >            return cursor - 1;
1351          }
1352  
1353 <        public Iterator<E> iterator() {
1354 <            synchronized(base) {
1355 <                return new VectorSubListIterator(this, 0);
1353 >        public E previous() {
1354 >            synchronized (Vector.this) {
1355 >                checkForComodification();
1356 >                int i = cursor - 1;
1357 >                if (i < 0)
1358 >                    throw new NoSuchElementException();
1359 >                cursor = i;
1360 >                return elementData(lastRet = i);
1361              }
1362          }
1363  
1364 <        public synchronized ListIterator<E> listIterator() {
1365 <            synchronized(base) {
1366 <                return new VectorSubListIterator(this, 0);
1364 >        public void set(E e) {
1365 >            if (lastRet == -1)
1366 >                throw new IllegalStateException();
1367 >            synchronized (Vector.this) {
1368 >                checkForComodification();
1369 >                Vector.this.set(lastRet, e);
1370              }
1371          }
1372  
1373 <        public ListIterator<E> listIterator(int index) {
1374 <            synchronized(base) {
1375 <                if (index < 0 || index > length)
1376 <                    throw indexError(index);
1377 <                return new VectorSubListIterator(this, index);
1373 >        public void add(E e) {
1374 >            int i = cursor;
1375 >            synchronized (Vector.this) {
1376 >                checkForComodification();
1377 >                Vector.this.add(i, e);
1378 >                expectedModCount = modCount;
1379              }
1380 +            cursor = i + 1;
1381 +            lastRet = -1;
1382          }
1383 +    }
1384  
1385 <        /**
1386 <         * Same idea as VectorIterator, except routing structural
1387 <         * change operations through the sublist.
1388 <         */
1389 <        private static final class VectorSubListIterator<E> implements ListIterator<E> {
1390 <            final Vector<E> base;         // base list
1391 <            final VectorSubList<E> outer; // Sublist creating this iteraor
1392 <            final int offset;             // cursor offset wrt base
1393 <            int cursor;                   // Current index
1394 <            int fence;                    // Upper bound on cursor
1395 <            int lastRet;                  // Index of returned element, or -1
1396 <            int expectedModCount;         // Expected modCount of base Vector
1397 <
1398 <            VectorSubListIterator(VectorSubList<E> list, int index) {
1399 <                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 <            }
1385 >    /**
1386 >     * @throws NullPointerException {@inheritDoc}
1387 >     */
1388 >    @Override
1389 >    public synchronized void forEach(Consumer<? super E> action) {
1390 >        Objects.requireNonNull(action);
1391 >        final int expectedModCount = modCount;
1392 >        final Object[] es = elementData;
1393 >        final int size = elementCount;
1394 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1395 >            action.accept(elementAt(es, i));
1396 >        if (modCount != expectedModCount)
1397 >            throw new ConcurrentModificationException();
1398 >        // checkInvariants();
1399 >    }
1400  
1401 <            public boolean hasPrevious() {
1402 <                return cursor > 0;
1403 <            }
1401 >    /**
1402 >     * @throws NullPointerException {@inheritDoc}
1403 >     */
1404 >    @Override
1405 >    public synchronized void replaceAll(UnaryOperator<E> operator) {
1406 >        Objects.requireNonNull(operator);
1407 >        final int expectedModCount = modCount;
1408 >        final Object[] es = elementData;
1409 >        final int size = elementCount;
1410 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1411 >            es[i] = operator.apply(elementAt(es, i));
1412 >        if (modCount != expectedModCount)
1413 >            throw new ConcurrentModificationException();
1414 >        // TODO(8203662): remove increment of modCount from ...
1415 >        modCount++;
1416 >        // checkInvariants();
1417 >    }
1418  
1419 <            public int nextIndex() {
1420 <                return cursor;
1421 <            }
1419 >    @SuppressWarnings("unchecked")
1420 >    @Override
1421 >    public synchronized void sort(Comparator<? super E> c) {
1422 >        final int expectedModCount = modCount;
1423 >        Arrays.sort((E[]) elementData, 0, elementCount, c);
1424 >        if (modCount != expectedModCount)
1425 >            throw new ConcurrentModificationException();
1426 >        modCount++;
1427 >        // checkInvariants();
1428 >    }
1429  
1430 <            public int previousIndex() {
1431 <                return cursor - 1;
1432 <            }
1430 >    /**
1431 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1432 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1433 >     * list.
1434 >     *
1435 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1436 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1437 >     * Overriding implementations should document the reporting of additional
1438 >     * characteristic values.
1439 >     *
1440 >     * @return a {@code Spliterator} over the elements in this list
1441 >     * @since 1.8
1442 >     */
1443 >    @Override
1444 >    public Spliterator<E> spliterator() {
1445 >        return new VectorSpliterator(null, 0, -1, 0);
1446 >    }
1447  
1448 <            public E next() {
1449 <                int i = cursor;
1450 <                if (cursor >= fence)
1451 <                    throw new NoSuchElementException();
1452 <                Object next = base.iteratorGet(i + offset, expectedModCount);
1453 <                lastRet = i;
1383 <                cursor = i + 1;
1384 <                return (E)next;
1385 <            }
1448 >    /** Similar to ArrayList Spliterator */
1449 >    final class VectorSpliterator implements Spliterator<E> {
1450 >        private Object[] array;
1451 >        private int index; // current index, modified on advance/split
1452 >        private int fence; // -1 until used; then one past last index
1453 >        private int expectedModCount; // initialized when fence set
1454  
1455 <            public E previous() {
1456 <                int i = cursor - 1;
1457 <                if (i < 0)
1458 <                    throw new NoSuchElementException();
1459 <                Object prev = base.iteratorGet(i + offset, expectedModCount);
1460 <                lastRet = i;
1461 <                cursor = i;
1462 <                return (E)prev;
1395 <            }
1455 >        /** Creates new spliterator covering the given range. */
1456 >        VectorSpliterator(Object[] array, int origin, int fence,
1457 >                          int expectedModCount) {
1458 >            this.array = array;
1459 >            this.index = origin;
1460 >            this.fence = fence;
1461 >            this.expectedModCount = expectedModCount;
1462 >        }
1463  
1464 <            public void set(E e) {
1465 <                if (lastRet < 0)
1466 <                    throw new IllegalStateException();
1467 <                if (base.modCount != expectedModCount)
1468 <                    throw new ConcurrentModificationException();
1469 <                try {
1470 <                    outer.set(lastRet, e);
1404 <                    expectedModCount = base.modCount;
1405 <                } catch (IndexOutOfBoundsException ex) {
1406 <                    throw new ConcurrentModificationException();
1464 >        private int getFence() { // initialize on first use
1465 >            int hi;
1466 >            if ((hi = fence) < 0) {
1467 >                synchronized (Vector.this) {
1468 >                    array = elementData;
1469 >                    expectedModCount = modCount;
1470 >                    hi = fence = elementCount;
1471                  }
1472              }
1473 +            return hi;
1474 +        }
1475  
1476 <            public void remove() {
1477 <                int i = lastRet;
1478 <                if (i < 0)
1479 <                    throw new IllegalStateException();
1480 <                if (base.modCount != expectedModCount)
1476 >        public Spliterator<E> trySplit() {
1477 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1478 >            return (lo >= mid) ? null :
1479 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1480 >        }
1481 >
1482 >        @SuppressWarnings("unchecked")
1483 >        public boolean tryAdvance(Consumer<? super E> action) {
1484 >            Objects.requireNonNull(action);
1485 >            int i;
1486 >            if (getFence() > (i = index)) {
1487 >                index = i + 1;
1488 >                action.accept((E)array[i]);
1489 >                if (modCount != expectedModCount)
1490                      throw new ConcurrentModificationException();
1491 <                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 <                }
1491 >                return true;
1492              }
1493 +            return false;
1494 +        }
1495  
1496 <            public void add(E e) {
1497 <                if (base.modCount != expectedModCount)
1498 <                    throw new ConcurrentModificationException();
1499 <                try {
1500 <                    int i = cursor;
1501 <                    outer.add(i, e);
1502 <                    cursor = i + 1;
1503 <                    lastRet = -1;
1504 <                    fence = outer.length;
1505 <                    expectedModCount = base.modCount;
1438 <                } catch (IndexOutOfBoundsException ex) {
1439 <                    throw new ConcurrentModificationException();
1440 <                }
1441 <            }
1496 >        @SuppressWarnings("unchecked")
1497 >        public void forEachRemaining(Consumer<? super E> action) {
1498 >            Objects.requireNonNull(action);
1499 >            final int hi = getFence();
1500 >            final Object[] a = array;
1501 >            int i;
1502 >            for (i = index, index = hi; i < hi; i++)
1503 >                action.accept((E) a[i]);
1504 >            if (modCount != expectedModCount)
1505 >                throw new ConcurrentModificationException();
1506          }
1443    }
1444 }
1507  
1508 +        public long estimateSize() {
1509 +            return getFence() - index;
1510 +        }
1511  
1512 +        public int characteristics() {
1513 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1514 +        }
1515 +    }
1516  
1517 +    void checkInvariants() {
1518 +        // assert elementCount >= 0;
1519 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1520 +    }
1521 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines