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.35 by jsr166, Sun Nov 13 21:07:40 2016 UTC

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