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.17 by jsr166, Mon Jun 26 00:17:48 2006 UTC vs.
Revision 1.30 by jsr166, Thu Nov 3 20:49:07 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 2006 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Oracle designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Oracle in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
27  
28 + import java.util.function.Consumer;
29 + import java.util.function.Predicate;
30 + import java.util.function.UnaryOperator;
31 +
32   /**
33   * The {@code Vector} 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 <     * This implements the unsynchronized semantics of ensureCapacity.
243 <     * Synchronized methods in this class can internally call this
244 <     * method for ensuring capacity without incurring the cost of an
245 <     * extra synchronization.
246 <     *
247 <     * @see #ensureCapacity(int)
248 <     */
249 <    private void ensureCapacityHelper(int minCapacity) {
250 <        int oldCapacity = elementData.length;
251 <        if (minCapacity > oldCapacity) {
252 <            Object[] oldData = elementData;
253 <            int newCapacity = (capacityIncrement > 0) ?
254 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
255 <            if (newCapacity < minCapacity) {
256 <                newCapacity = minCapacity;
257 <            }
258 <            elementData = Arrays.copyOf(elementData, newCapacity);
259 <        }
242 >     * The maximum size of array to allocate (unless necessary).
243 >     * Some VMs reserve some header words in an array.
244 >     * Attempts to allocate larger arrays may result in
245 >     * OutOfMemoryError: Requested array size exceeds VM limit
246 >     */
247 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
248 >
249 >    /**
250 >     * Increases the capacity to ensure that it can hold at least the
251 >     * number of elements specified by the minimum capacity argument.
252 >     *
253 >     * @param minCapacity the desired minimum capacity
254 >     * @throws OutOfMemoryError if minCapacity is less than zero
255 >     */
256 >    private Object[] grow(int minCapacity) {
257 >        return elementData = Arrays.copyOf(elementData,
258 >                                           newCapacity(minCapacity));
259 >    }
260 >
261 >    private Object[] grow() {
262 >        return grow(elementCount + 1);
263 >    }
264 >
265 >    /**
266 >     * Returns a capacity at least as large as the given minimum capacity.
267 >     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
268 >     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
269 >     *
270 >     * @param minCapacity the desired minimum capacity
271 >     * @throws OutOfMemoryError if minCapacity is less than zero
272 >     */
273 >    private int newCapacity(int minCapacity) {
274 >        // overflow-conscious code
275 >        int oldCapacity = elementData.length;
276 >        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
277 >                                         capacityIncrement : oldCapacity);
278 >        if (newCapacity - minCapacity <= 0) {
279 >            if (minCapacity < 0) // overflow
280 >                throw new OutOfMemoryError();
281 >            return minCapacity;
282 >        }
283 >        return (newCapacity - MAX_ARRAY_SIZE <= 0)
284 >            ? newCapacity
285 >            : hugeCapacity(minCapacity);
286 >    }
287 >
288 >    private static int hugeCapacity(int minCapacity) {
289 >        if (minCapacity < 0) // overflow
290 >            throw new OutOfMemoryError();
291 >        return (minCapacity > MAX_ARRAY_SIZE) ?
292 >            Integer.MAX_VALUE :
293 >            MAX_ARRAY_SIZE;
294      }
295  
296      /**
# 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 E nextElement() {
365 <                synchronized (Vector.this) {
366 <                    if (count < elementCount) {
367 <                        return (E)elementData[count++];
368 <                    }
369 <                }
370 <                throw new NoSuchElementException("Vector Enumeration");
371 <            }
372 <        };
360 >            public boolean hasMoreElements() {
361 >                return count < elementCount;
362 >            }
363 >
364 >            public E nextElement() {
365 >                synchronized (Vector.this) {
366 >                    if (count < elementCount) {
367 >                        return elementData(count++);
368 >                    }
369 >                }
370 >                throw new NoSuchElementException("Vector Enumeration");
371 >            }
372 >        };
373      }
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      /**
# Line 452 | Line 517 | public class Vector<E>
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      }
589  
590      /**
# Line 543 | Line 608 | public class Vector<E>
608       * @param      obj     the component to insert
609       * @param      index   where to insert the new component
610       * @throws ArrayIndexOutOfBoundsException if the index is out of range
611 <     *         ({@code index < 0 || index > size()})
611 >     *         ({@code index < 0 || index > size()})
612       */
613      public synchronized void insertElementAt(E obj, int index) {
614 <        modCount++;
615 <        if (index > elementCount) {
616 <            throw new ArrayIndexOutOfBoundsException(index
617 <                                                     + " > " + elementCount);
618 <        }
619 <        ensureCapacityHelper(elementCount + 1);
620 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
621 <        elementData[index] = obj;
622 <        elementCount++;
614 >        if (index > elementCount) {
615 >            throw new ArrayIndexOutOfBoundsException(index
616 >                                                     + " > " + elementCount);
617 >        }
618 >        modCount++;
619 >        final int s = elementCount;
620 >        Object[] elementData = this.elementData;
621 >        if (s == elementData.length)
622 >            elementData = grow();
623 >        System.arraycopy(elementData, index,
624 >                         elementData, index + 1,
625 >                         s - index);
626 >        elementData[index] = obj;
627 >        elementCount = s + 1;
628      }
629  
630      /**
# Line 563 | Line 633 | public class Vector<E>
633       * increased if its size becomes greater than its capacity.
634       *
635       * <p>This method is identical in functionality to the
636 <     * {@link #remove(Object)} method (which is part of the
637 <     * {@link List} interface).
636 >     * {@link #add(Object) add(E)}
637 >     * method (which is part of the {@link List} interface).
638       *
639       * @param   obj   the component to be added
640       */
641      public synchronized void addElement(E obj) {
642 <        modCount++;
643 <        ensureCapacityHelper(elementCount + 1);
574 <        elementData[elementCount++] = obj;
642 >        modCount++;
643 >        add(obj, elementData, elementCount);
644      }
645  
646      /**
# Line 581 | Line 650 | public class Vector<E>
650       * object's index is shifted downward to have an index one smaller
651       * than the value it had previously.
652       *
653 <     * <p>This method is identical in functionality to the remove(Object)
654 <     * method (which is part of the List interface).
653 >     * <p>This method is identical in functionality to the
654 >     * {@link #remove(Object)} method (which is part of the
655 >     * {@link List} interface).
656       *
657       * @param   obj   the component to be removed
658       * @return  {@code true} if the argument was a component of this
659       *          vector; {@code false} otherwise.
590     * @see     List#remove(Object)
591     * @see     List
660       */
661      public synchronized boolean removeElement(Object obj) {
662 <        modCount++;
663 <        int i = indexOf(obj);
664 <        if (i >= 0) {
665 <            removeElementAt(i);
666 <            return true;
667 <        }
668 <        return false;
662 >        modCount++;
663 >        int i = indexOf(obj);
664 >        if (i >= 0) {
665 >            removeElementAt(i);
666 >            return true;
667 >        }
668 >        return false;
669      }
670  
671      /**
# Line 607 | Line 675 | public class Vector<E>
675       * method (which is part of the {@link List} interface).
676       */
677      public synchronized void removeAllElements() {
678 <        modCount++;
679 <        // Let gc do its work
680 <        for (int i = 0; i < elementCount; i++)
613 <            elementData[i] = null;
678 >        // Let gc do its work
679 >        for (int i = 0; i < elementCount; i++)
680 >            elementData[i] = null;
681  
682 <        elementCount = 0;
682 >        modCount++;
683 >        elementCount = 0;
684      }
685  
686      /**
# Line 623 | Line 691 | public class Vector<E>
691       * @return  a clone of this vector
692       */
693      public synchronized Object clone() {
694 <        try {
695 <            Vector<E> v = (Vector<E>) super.clone();
696 <            v.elementData = Arrays.copyOf(elementData, elementCount);
697 <            v.modCount = 0;
698 <            return v;
699 <        } catch (CloneNotSupportedException e) {
700 <            // this shouldn't happen, since we are Cloneable
701 <            throw new InternalError();
702 <        }
694 >        try {
695 >            @SuppressWarnings("unchecked")
696 >                Vector<E> v = (Vector<E>) super.clone();
697 >            v.elementData = Arrays.copyOf(elementData, elementCount);
698 >            v.modCount = 0;
699 >            return v;
700 >        } catch (CloneNotSupportedException e) {
701 >            // this shouldn't happen, since we are Cloneable
702 >            throw new InternalError(e);
703 >        }
704      }
705  
706      /**
# Line 658 | Line 727 | public class Vector<E>
727       * of the Vector <em>only</em> if the caller knows that the Vector
728       * does not contain any null elements.)
729       *
730 +     * @param <T> type of array elements. The same type as {@code <E>} or a
731 +     * supertype of {@code <E>}.
732       * @param a the array into which the elements of the Vector are to
733 <     *          be stored, if it is big enough; otherwise, a new array of the
734 <     *          same runtime type is allocated for this purpose.
733 >     *          be stored, if it is big enough; otherwise, a new array of the
734 >     *          same runtime type is allocated for this purpose.
735       * @return an array containing the elements of the Vector
736 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
737 <     * of the runtime type of every element in this Vector
736 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
737 >     * a supertype of the runtime type, {@code <E>}, of every element in this
738 >     * Vector
739       * @throws NullPointerException if the given array is null
740       * @since 1.2
741       */
742 +    @SuppressWarnings("unchecked")
743      public synchronized <T> T[] toArray(T[] a) {
744          if (a.length < elementCount)
745              return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
746  
747 <        System.arraycopy(elementData, 0, a, 0, elementCount);
747 >        System.arraycopy(elementData, 0, a, 0, elementCount);
748  
749          if (a.length > elementCount)
750              a[elementCount] = null;
# Line 681 | Line 754 | public class Vector<E>
754  
755      // Positional Access Operations
756  
757 +    @SuppressWarnings("unchecked")
758 +    E elementData(int index) {
759 +        return (E) elementData[index];
760 +    }
761 +
762      /**
763       * Returns the element at the specified position in this Vector.
764       *
# Line 691 | Line 769 | public class Vector<E>
769       * @since 1.2
770       */
771      public synchronized E get(int index) {
772 <        if (index >= elementCount)
773 <            throw new ArrayIndexOutOfBoundsException(index);
772 >        if (index >= elementCount)
773 >            throw new ArrayIndexOutOfBoundsException(index);
774  
775 <        return (E)elementData[index];
775 >        return elementData(index);
776      }
777  
778      /**
# Line 705 | Line 783 | public class Vector<E>
783       * @param element element to be stored at the specified position
784       * @return the element previously at the specified position
785       * @throws ArrayIndexOutOfBoundsException if the index is out of range
786 <     *         ({@code index < 0 || index >= size()})
786 >     *         ({@code index < 0 || index >= size()})
787       * @since 1.2
788       */
789      public synchronized E set(int index, E element) {
790 <        if (index >= elementCount)
791 <            throw new ArrayIndexOutOfBoundsException(index);
790 >        if (index >= elementCount)
791 >            throw new ArrayIndexOutOfBoundsException(index);
792  
793 <        Object oldValue = elementData[index];
794 <        elementData[index] = element;
795 <        return (E)oldValue;
793 >        E oldValue = elementData(index);
794 >        elementData[index] = element;
795 >        return oldValue;
796 >    }
797 >
798 >    /**
799 >     * This helper method split out from add(E) to keep method
800 >     * bytecode size under 35 (the -XX:MaxInlineSize default value),
801 >     * which helps when add(E) is called in a C1-compiled loop.
802 >     */
803 >    private void add(E e, Object[] elementData, int s) {
804 >        if (s == elementData.length)
805 >            elementData = grow();
806 >        elementData[s] = e;
807 >        elementCount = s + 1;
808      }
809  
810      /**
# Line 725 | Line 815 | public class Vector<E>
815       * @since 1.2
816       */
817      public synchronized boolean add(E e) {
818 <        modCount++;
819 <        ensureCapacityHelper(elementCount + 1);
730 <        elementData[elementCount++] = e;
818 >        modCount++;
819 >        add(e, elementData, elementCount);
820          return true;
821      }
822  
# Line 735 | Line 824 | public class Vector<E>
824       * Removes the first occurrence of the specified element in this Vector
825       * If the Vector does not contain the element, it is unchanged.  More
826       * formally, removes the element with the lowest index i such that
827 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
827 >     * {@code Objects.equals(o, get(i))} (if such
828       * an element exists).
829       *
830       * @param o element to be removed from this Vector, if present
# Line 766 | Line 855 | public class Vector<E>
855       * Shifts any subsequent elements to the left (subtracts one from their
856       * indices).  Returns the element that was removed from the Vector.
857       *
858 <     * @exception ArrayIndexOutOfBoundsException index out of range (index
859 <     *            &lt; 0 || index &gt;= size())
858 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
859 >     *         ({@code index < 0 || index >= size()})
860       * @param index the index of the element to be removed
861       * @return element that was removed
862       * @since 1.2
863       */
864      public synchronized E remove(int index) {
865 <        modCount++;
866 <        if (index >= elementCount)
867 <            throw new ArrayIndexOutOfBoundsException(index);
868 <        Object oldValue = elementData[index];
780 <
781 <        int numMoved = elementCount - index - 1;
782 <        if (numMoved > 0)
783 <            System.arraycopy(elementData, index+1, elementData, index,
784 <                             numMoved);
785 <        elementData[--elementCount] = null; // Let gc do its work
865 >        modCount++;
866 >        if (index >= elementCount)
867 >            throw new ArrayIndexOutOfBoundsException(index);
868 >        E oldValue = elementData(index);
869  
870 <        return (E)oldValue;
870 >        int numMoved = elementCount - index - 1;
871 >        if (numMoved > 0)
872 >            System.arraycopy(elementData, index+1, elementData, index,
873 >                             numMoved);
874 >        elementData[--elementCount] = null; // Let gc do its work
875 >
876 >        return oldValue;
877      }
878  
879      /**
# Line 806 | Line 895 | public class Vector<E>
895       * @param   c a collection whose elements will be tested for containment
896       *          in this Vector
897       * @return true if this Vector contains all of the elements in the
898 <     *         specified collection
898 >     *         specified collection
899       * @throws NullPointerException if the specified collection is null
900       */
901      public synchronized boolean containsAll(Collection<?> c) {
# Line 826 | Line 915 | public class Vector<E>
915       * @throws NullPointerException if the specified collection is null
916       * @since 1.2
917       */
918 <    public synchronized boolean addAll(Collection<? extends E> c) {
830 <        modCount++;
918 >    public boolean addAll(Collection<? extends E> c) {
919          Object[] a = c.toArray();
920 +        modCount++;
921          int numNew = a.length;
922 <        ensureCapacityHelper(elementCount + numNew);
923 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
924 <        elementCount += numNew;
925 <        return numNew != 0;
922 >        if (numNew == 0)
923 >            return false;
924 >        synchronized (this) {
925 >            Object[] elementData = this.elementData;
926 >            final int s = elementCount;
927 >            if (numNew > elementData.length - s)
928 >                elementData = grow(s + numNew);
929 >            System.arraycopy(a, 0, elementData, s, numNew);
930 >            elementCount = s + numNew;
931 >            return true;
932 >        }
933      }
934  
935      /**
# Line 844 | Line 940 | public class Vector<E>
940       * @return true if this Vector changed as a result of the call
941       * @throws ClassCastException if the types of one or more elements
942       *         in this vector are incompatible with the specified
943 <     *         collection (optional)
943 >     *         collection
944 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
945       * @throws NullPointerException if this vector contains one or more null
946       *         elements and the specified collection does not support null
947 <     *         elements (optional), or if the specified collection is null
947 >     *         elements
948 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
949 >     *         or if the specified collection is null
950       * @since 1.2
951       */
952      public synchronized boolean removeAll(Collection<?> c) {
# Line 864 | Line 963 | public class Vector<E>
963       * @return true if this Vector changed as a result of the call
964       * @throws ClassCastException if the types of one or more elements
965       *         in this vector are incompatible with the specified
966 <     *         collection (optional)
966 >     *         collection
967 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
968       * @throws NullPointerException if this vector contains one or more null
969       *         elements and the specified collection does not support null
970 <     *         elements (optional), or if the specified collection is null
970 >     *         elements
971 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
972 >     *         or if the specified collection is null
973       * @since 1.2
974       */
975 <    public synchronized boolean retainAll(Collection<?> c)  {
975 >    public synchronized boolean retainAll(Collection<?> c) {
976          return super.retainAll(c);
977      }
978  
# Line 886 | Line 988 | public class Vector<E>
988       *              specified collection
989       * @param c elements to be inserted into this Vector
990       * @return {@code true} if this Vector changed as a result of the call
991 <     * @exception ArrayIndexOutOfBoundsException index out of range (index
992 <     *            &lt; 0 || index &gt; size())
991 >     * @throws ArrayIndexOutOfBoundsException if the index is out of range
992 >     *         ({@code index < 0 || index > size()})
993       * @throws NullPointerException if the specified collection is null
994       * @since 1.2
995       */
996      public synchronized boolean addAll(int index, Collection<? extends E> c) {
997 <        modCount++;
998 <        if (index < 0 || index > elementCount)
897 <            throw new ArrayIndexOutOfBoundsException(index);
997 >        if (index < 0 || index > elementCount)
998 >            throw new ArrayIndexOutOfBoundsException(index);
999  
1000          Object[] a = c.toArray();
1001 <        int numNew = a.length;
1002 <        ensureCapacityHelper(elementCount + numNew);
1003 <
1004 <        int numMoved = elementCount - index;
1005 <        if (numMoved > 0)
1006 <            System.arraycopy(elementData, index, elementData, index + numNew,
1007 <                             numMoved);
1008 <
1001 >        modCount++;
1002 >        int numNew = a.length;
1003 >        if (numNew == 0)
1004 >            return false;
1005 >        Object[] elementData = this.elementData;
1006 >        final int s = elementCount;
1007 >        if (numNew > elementData.length - s)
1008 >            elementData = grow(s + numNew);
1009 >
1010 >        int numMoved = s - index;
1011 >        if (numMoved > 0)
1012 >            System.arraycopy(elementData, index,
1013 >                             elementData, index + numNew,
1014 >                             numMoved);
1015          System.arraycopy(a, 0, elementData, index, numNew);
1016 <        elementCount += numNew;
1017 <        return numNew != 0;
1016 >        elementCount = s + numNew;
1017 >        return true;
1018      }
1019  
1020      /**
# Line 915 | Line 1022 | public class Vector<E>
1022       * true if and only if the specified Object is also a List, both Lists
1023       * have the same size, and all corresponding pairs of elements in the two
1024       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1025 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1026 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1025 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1026 >     * In other words, two Lists are defined to be
1027       * equal if they contain the same elements in the same order.
1028       *
1029       * @param o the Object to be compared for equality with this Vector
# Line 942 | Line 1049 | public class Vector<E>
1049      }
1050  
1051      /**
1052 <     * Removes from this List all of the elements whose index is between
1053 <     * fromIndex, inclusive and toIndex, exclusive.  Shifts any succeeding
1054 <     * elements to the left (reduces their index).
1055 <     * This call shortens the Vector by (toIndex - fromIndex) elements.  (If
1056 <     * toIndex==fromIndex, this operation has no effect.)
1052 >     * Returns a view of the portion of this List between fromIndex,
1053 >     * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1054 >     * equal, the returned List is empty.)  The returned List is backed by this
1055 >     * List, so changes in the returned List are reflected in this List, and
1056 >     * vice-versa.  The returned List supports all of the optional List
1057 >     * operations supported by this List.
1058 >     *
1059 >     * <p>This method eliminates the need for explicit range operations (of
1060 >     * the sort that commonly exist for arrays).  Any operation that expects
1061 >     * a List can be used as a range operation by operating on a subList view
1062 >     * instead of a whole List.  For example, the following idiom
1063 >     * removes a range of elements from a List:
1064 >     * <pre>
1065 >     *      list.subList(from, to).clear();
1066 >     * </pre>
1067 >     * Similar idioms may be constructed for indexOf and lastIndexOf,
1068 >     * and all of the algorithms in the Collections class can be applied to
1069 >     * a subList.
1070 >     *
1071 >     * <p>The semantics of the List returned by this method become undefined if
1072 >     * the backing list (i.e., this List) is <i>structurally modified</i> in
1073 >     * any way other than via the returned List.  (Structural modifications are
1074 >     * those that change the size of the List, or otherwise perturb it in such
1075 >     * a fashion that iterations in progress may yield incorrect results.)
1076       *
1077 <     * @param fromIndex index of first element to be removed
1078 <     * @param toIndex index after last element to be removed
1077 >     * @param fromIndex low endpoint (inclusive) of the subList
1078 >     * @param toIndex high endpoint (exclusive) of the subList
1079 >     * @return a view of the specified range within this List
1080 >     * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1081 >     *         {@code (fromIndex < 0 || toIndex > size)}
1082 >     * @throws IllegalArgumentException if the endpoint indices are out of order
1083 >     *         {@code (fromIndex > toIndex)}
1084 >     */
1085 >    public synchronized List<E> subList(int fromIndex, int toIndex) {
1086 >        return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1087 >                                            this);
1088 >    }
1089 >
1090 >    /**
1091 >     * Removes from this list all of the elements whose index is between
1092 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1093 >     * Shifts any succeeding elements to the left (reduces their index).
1094 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1095 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
1096       */
1097      protected synchronized void removeRange(int fromIndex, int toIndex) {
1098 <        modCount++;
956 <        int numMoved = elementCount - toIndex;
1098 >        int numMoved = elementCount - toIndex;
1099          System.arraycopy(elementData, toIndex, elementData, fromIndex,
1100                           numMoved);
1101  
1102 <        // Let gc do its work
1103 <        int newElementCount = elementCount - (toIndex-fromIndex);
1104 <        while (elementCount != newElementCount)
1105 <            elementData[--elementCount] = null;
1102 >        // Let gc do its work
1103 >        modCount++;
1104 >        int newElementCount = elementCount - (toIndex-fromIndex);
1105 >        while (elementCount != newElementCount)
1106 >            elementData[--elementCount] = null;
1107      }
1108  
1109      /**
1110       * Save the state of the {@code Vector} instance to a stream (that
1111 <     * is, serialize it).  This method is present merely for synchronization.
1112 <     * It just calls the default writeObject method.
1111 >     * is, serialize it).
1112 >     * This method performs synchronization to ensure the consistency
1113 >     * of the serialized data.
1114       */
1115 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1116 <        throws java.io.IOException
1117 <    {
1118 <        s.defaultWriteObject();
1115 >    private void writeObject(java.io.ObjectOutputStream s)
1116 >            throws java.io.IOException {
1117 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1118 >        final Object[] data;
1119 >        synchronized (this) {
1120 >            fields.put("capacityIncrement", capacityIncrement);
1121 >            fields.put("elementCount", elementCount);
1122 >            data = elementData.clone();
1123 >        }
1124 >        fields.put("elementData", data);
1125 >        s.writeFields();
1126      }
1127  
1128      /**
1129 <     * Returns a list-iterator of the elements in this list (in proper
1129 >     * Returns a list iterator over the elements in this list (in proper
1130       * sequence), starting at the specified position in the list.
1131 <     * Obeys the general contract of {@link List#listIterator(int)}.
1131 >     * The specified index indicates the first element that would be
1132 >     * returned by an initial call to {@link ListIterator#next next}.
1133 >     * An initial call to {@link ListIterator#previous previous} would
1134 >     * return the element with the specified index minus one.
1135 >     *
1136 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1137       *
982     * <p>The list-iterator is <i>fail-fast</i>: if the list is structurally
983     * modified at any time after the Iterator is created, in any way except
984     * through the list-iterator's own {@code remove} or {@code add}
985     * methods, the list-iterator will throw a
986     * {@code ConcurrentModificationException}.  Thus, in the face of
987     * concurrent modification, the iterator fails quickly and cleanly, rather
988     * than risking arbitrary, non-deterministic behavior at an undetermined
989     * time in the future.
990     *
991     * @param index index of the first element to be returned from the
992     *        list-iterator (by a call to {@link ListIterator#next})
993     * @return a list-iterator of the elements in this list (in proper
994     *         sequence), starting at the specified position in the list
1138       * @throws IndexOutOfBoundsException {@inheritDoc}
1139       */
1140      public synchronized ListIterator<E> listIterator(int index) {
1141 <        if (index < 0 || index > elementCount)
1141 >        if (index < 0 || index > elementCount)
1142              throw new IndexOutOfBoundsException("Index: "+index);
1143 <        return new VectorIterator(index, elementCount);
1143 >        return new ListItr(index);
1144      }
1145  
1146      /**
1147 <     * {@inheritDoc}
1147 >     * Returns a list iterator over the elements in this list (in proper
1148 >     * sequence).
1149 >     *
1150 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1151 >     *
1152 >     * @see #listIterator(int)
1153       */
1154      public synchronized ListIterator<E> listIterator() {
1155 <        return new VectorIterator(0, elementCount);
1155 >        return new ListItr(0);
1156      }
1157  
1158      /**
1159       * Returns an iterator over the elements in this list in proper sequence.
1160       *
1161 +     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1162 +     *
1163       * @return an iterator over the elements in this list in proper sequence
1164       */
1165      public synchronized Iterator<E> iterator() {
1166 <        return new VectorIterator(0, elementCount);
1166 >        return new Itr();
1167      }
1168  
1169      /**
1170 <     * Helper method to access array elements under synchronization by
1021 <     * iterators. The caller performs index check with respect to
1022 <     * expected bounds, so errors accessing the element are reported
1023 <     * as ConcurrentModificationExceptions.
1170 >     * An optimized version of AbstractList.Itr
1171       */
1172 <    final synchronized Object iteratorGet(int index, int expectedModCount) {
1173 <        if (modCount == expectedModCount) {
1174 <            try {
1175 <                return elementData[index];
1029 <            } catch(IndexOutOfBoundsException fallThrough) {
1030 <            }
1031 <        }
1032 <        throw new ConcurrentModificationException();
1033 <    }
1034 <
1035 <    /**
1036 <     * Streamlined specialization of AbstractList version of iterator.
1037 <     * Locally perfroms bounds checks, but relies on outer Vector
1038 <     * to access elements under synchronization.
1039 <     */
1040 <    private final class VectorIterator implements ListIterator<E> {
1041 <        int cursor;              // Index of next element to return;
1042 <        int fence;               // Upper bound on cursor (cache of size())
1043 <        int lastRet;             // Index of last element, or -1 if no such
1044 <        int expectedModCount;    // To check for CME
1045 <
1046 <        VectorIterator(int index, int fence) {
1047 <            this.cursor = index;
1048 <            this.fence = fence;
1049 <            this.lastRet = -1;
1050 <            this.expectedModCount = Vector.this.modCount;
1051 <        }
1052 <
1053 <        public boolean hasNext() {
1054 <            return cursor < fence;
1055 <        }
1056 <
1057 <        public boolean hasPrevious() {
1058 <            return cursor > 0;
1059 <        }
1060 <
1061 <        public int nextIndex() {
1062 <            return cursor;
1063 <        }
1064 <
1065 <        public int previousIndex() {
1066 <            return cursor - 1;
1067 <        }
1172 >    private class Itr implements Iterator<E> {
1173 >        int cursor;       // index of next element to return
1174 >        int lastRet = -1; // index of last element returned; -1 if no such
1175 >        int expectedModCount = modCount;
1176  
1177 <        public E next() {
1178 <            int i = cursor;
1179 <            if (i >= fence)
1180 <                throw new NoSuchElementException();
1073 <            Object next = Vector.this.iteratorGet(i, expectedModCount);
1074 <            lastRet = i;
1075 <            cursor = i + 1;
1076 <            return (E)next;
1077 <        }
1078 <
1079 <        public E previous() {
1080 <            int i = cursor - 1;
1081 <            if (i < 0)
1082 <                throw new NoSuchElementException();
1083 <            Object prev = Vector.this.iteratorGet(i, expectedModCount);
1084 <            lastRet = i;
1085 <            cursor = i;
1086 <            return (E)prev;
1177 >        public boolean hasNext() {
1178 >            // Racy but within spec, since modifications are checked
1179 >            // within or after synchronization in next/previous
1180 >            return cursor != elementCount;
1181          }
1182  
1183 <        public void set(E e) {
1184 <            if (lastRet < 0)
1185 <                throw new IllegalStateException();
1092 <            if (Vector.this.modCount != expectedModCount)
1093 <                throw new ConcurrentModificationException();
1094 <            try {
1095 <                Vector.this.set(lastRet, e);
1096 <                expectedModCount = Vector.this.modCount;
1097 <            } catch (IndexOutOfBoundsException ex) {
1098 <                throw new ConcurrentModificationException();
1099 <            }
1100 <        }
1101 <
1102 <        public void remove() {
1103 <            int i = lastRet;
1104 <            if (i < 0)
1105 <                throw new IllegalStateException();
1106 <            if (Vector.this.modCount != expectedModCount)
1107 <                throw new ConcurrentModificationException();
1108 <            try {
1109 <                Vector.this.remove(i);
1110 <                if (i < cursor)
1111 <                    cursor--;
1112 <                lastRet = -1;
1113 <                fence = Vector.this.size();
1114 <                expectedModCount = Vector.this.modCount;
1115 <            } catch (IndexOutOfBoundsException ex) {
1116 <                throw new ConcurrentModificationException();
1117 <            }
1118 <        }
1119 <
1120 <        public void add(E e) {
1121 <            if (Vector.this.modCount != expectedModCount)
1122 <                throw new ConcurrentModificationException();
1123 <            try {
1183 >        public E next() {
1184 >            synchronized (Vector.this) {
1185 >                checkForComodification();
1186                  int i = cursor;
1187 <                Vector.this.add(i, e);
1187 >                if (i >= elementCount)
1188 >                    throw new NoSuchElementException();
1189                  cursor = i + 1;
1190 <                lastRet = -1;
1128 <                fence = Vector.this.size();
1129 <                expectedModCount = Vector.this.modCount;
1130 <            } catch (IndexOutOfBoundsException ex) {
1131 <                throw new ConcurrentModificationException();
1132 <            }
1133 <        }
1134 <    }
1135 <
1136 <    /**
1137 <     * Returns a view of the portion of this List between fromIndex,
1138 <     * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1139 <     * equal, the returned List is empty.)  The returned List is backed by this
1140 <     * List, so changes in the returned List are reflected in this List, and
1141 <     * vice-versa.  The returned List supports all of the optional List
1142 <     * operations supported by this List.
1143 <     *
1144 <     * <p>This method eliminates the need for explicit range operations (of
1145 <     * the sort that commonly exist for arrays).   Any operation that expects
1146 <     * a List can be used as a range operation by operating on a subList view
1147 <     * instead of a whole List.  For example, the following idiom
1148 <     * removes a range of elements from a List:
1149 <     * <pre>
1150 <     *      list.subList(from, to).clear();
1151 <     * </pre>
1152 <     * Similar idioms may be constructed for indexOf and lastIndexOf,
1153 <     * and all of the algorithms in the Collections class can be applied to
1154 <     * a subList.
1155 <     *
1156 <     * <p>The semantics of the List returned by this method become undefined if
1157 <     * the backing list (i.e., this List) is <i>structurally modified</i> in
1158 <     * any way other than via the returned List.  (Structural modifications are
1159 <     * those that change the size of the List, or otherwise perturb it in such
1160 <     * a fashion that iterations in progress may yield incorrect results.)
1161 <     *
1162 <     * @param fromIndex low endpoint (inclusive) of the subList
1163 <     * @param toIndex high endpoint (exclusive) of the subList
1164 <     * @return a view of the specified range within this List
1165 <     * @throws IndexOutOfBoundsException endpoint index value out of range
1166 <     *         <code>(fromIndex &lt; 0 || toIndex &gt; size)</code>
1167 <     * @throws IllegalArgumentException endpoint indices out of order
1168 <     *         <code>(fromIndex &gt; toIndex)</code>
1169 <     */
1170 <    public synchronized List<E> subList(int fromIndex, int toIndex) {
1171 <        return new VectorSubList(this, this, fromIndex, fromIndex, toIndex);
1172 <    }
1173 <
1174 <    /**
1175 <     * This class specializes the AbstractList version of SubList to
1176 <     * avoid the double-indirection penalty that would arise using a
1177 <     * synchronized wrapper, as well as to avoid some unnecessary
1178 <     * checks in sublist iterators.
1179 <     */
1180 <    private static final class VectorSubList<E> extends AbstractList<E> implements RandomAccess {
1181 <        final Vector<E> base;             // base list
1182 <        final AbstractList<E> parent;     // Creating list
1183 <        final int baseOffset;             // index wrt Vector
1184 <        final int parentOffset;           // index wrt parent
1185 <        int length;                       // length of sublist
1186 <
1187 <        VectorSubList(Vector<E> base, AbstractList<E> parent, int baseOffset,
1188 <                     int fromIndex, int toIndex) {
1189 <            if (fromIndex < 0)
1190 <                throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
1191 <            if (toIndex > parent.size())
1192 <                throw new IndexOutOfBoundsException("toIndex = " + toIndex);
1193 <            if (fromIndex > toIndex)
1194 <                throw new IllegalArgumentException("fromIndex(" + fromIndex +
1195 <                                                   ") > toIndex(" + toIndex + ")");
1196 <
1197 <            this.base = base;
1198 <            this.parent = parent;
1199 <            this.baseOffset = baseOffset;
1200 <            this.parentOffset = fromIndex;
1201 <            this.length = toIndex - fromIndex;
1202 <            modCount = base.modCount;
1203 <        }
1204 <
1205 <        /**
1206 <         * Returns an IndexOutOfBoundsException with nicer message
1207 <         */
1208 <        private IndexOutOfBoundsException indexError(int index) {
1209 <            return new IndexOutOfBoundsException("Index: " + index +
1210 <                                                 ", Size: " + length);
1211 <        }
1212 <
1213 <        public E set(int index, E element) {
1214 <            synchronized(base) {
1215 <                if (index < 0 || index >= length)
1216 <                    throw indexError(index);
1217 <                if (base.modCount != modCount)
1218 <                    throw new ConcurrentModificationException();
1219 <                return base.set(index + baseOffset, element);
1220 <            }
1221 <        }
1222 <
1223 <        public E get(int index) {
1224 <            synchronized(base) {
1225 <                if (index < 0 || index >= length)
1226 <                    throw indexError(index);
1227 <                if (base.modCount != modCount)
1228 <                    throw new ConcurrentModificationException();
1229 <                return base.get(index + baseOffset);
1230 <            }
1231 <        }
1232 <
1233 <        public int size() {
1234 <            synchronized(base) {
1235 <                if (base.modCount != modCount)
1236 <                    throw new ConcurrentModificationException();
1237 <                return length;
1190 >                return elementData(lastRet = i);
1191              }
1192          }
1193  
1194 <        public void add(int index, E element) {
1195 <            synchronized(base) {
1196 <                if (index < 0 || index > length)
1197 <                    throw indexError(index);
1198 <                if (base.modCount != modCount)
1199 <                    throw new ConcurrentModificationException();
1200 <                parent.add(index + parentOffset, element);
1248 <                length++;
1249 <                modCount = base.modCount;
1194 >        public void remove() {
1195 >            if (lastRet == -1)
1196 >                throw new IllegalStateException();
1197 >            synchronized (Vector.this) {
1198 >                checkForComodification();
1199 >                Vector.this.remove(lastRet);
1200 >                expectedModCount = modCount;
1201              }
1202 +            cursor = lastRet;
1203 +            lastRet = -1;
1204          }
1205  
1206 <        public E remove(int index) {
1207 <            synchronized(base) {
1208 <                if (index < 0 || index >= length)
1209 <                    throw indexError(index);
1210 <                if (base.modCount != modCount)
1211 <                    throw new ConcurrentModificationException();
1212 <                E result = parent.remove(index + parentOffset);
1213 <                length--;
1214 <                modCount = base.modCount;
1215 <                return result;
1216 <            }
1217 <        }
1265 <
1266 <        protected void removeRange(int fromIndex, int toIndex) {
1267 <            synchronized(base) {
1268 <                if (base.modCount != modCount)
1206 >        @Override
1207 >        public void forEachRemaining(Consumer<? super E> action) {
1208 >            Objects.requireNonNull(action);
1209 >            synchronized (Vector.this) {
1210 >                final int size = elementCount;
1211 >                int i = cursor;
1212 >                if (i >= size) {
1213 >                    return;
1214 >                }
1215 >        @SuppressWarnings("unchecked")
1216 >                final E[] elementData = (E[]) Vector.this.elementData;
1217 >                if (i >= elementData.length) {
1218                      throw new ConcurrentModificationException();
1219 <                parent.removeRange(fromIndex + parentOffset,
1220 <                                   toIndex + parentOffset);
1221 <                length -= (toIndex-fromIndex);
1222 <                modCount = base.modCount;
1219 >                }
1220 >                while (i != size && modCount == expectedModCount) {
1221 >                    action.accept(elementData[i++]);
1222 >                }
1223 >                // update once at end of iteration to reduce heap write traffic
1224 >                cursor = i;
1225 >                lastRet = i - 1;
1226 >                checkForComodification();
1227              }
1228          }
1229  
1230 <        public boolean addAll(Collection<? extends E> c) {
1231 <            return addAll(length, c);
1232 <        }
1280 <
1281 <        public boolean addAll(int index, Collection<? extends E> c) {
1282 <            synchronized(base) {
1283 <                if (index < 0 || index > length)
1284 <                    throw indexError(index);
1285 <                int cSize = c.size();
1286 <                if (cSize==0)
1287 <                    return false;
1288 <
1289 <                if (base.modCount != modCount)
1290 <                    throw new ConcurrentModificationException();
1291 <                parent.addAll(parentOffset + index, c);
1292 <                modCount = base.modCount;
1293 <                length += cSize;
1294 <                return true;
1295 <            }
1230 >        final void checkForComodification() {
1231 >            if (modCount != expectedModCount)
1232 >                throw new ConcurrentModificationException();
1233          }
1234 +    }
1235  
1236 <        public boolean equals(Object o) {
1237 <            synchronized(base) {return super.equals(o);}
1236 >    /**
1237 >     * An optimized version of AbstractList.ListItr
1238 >     */
1239 >    final class ListItr extends Itr implements ListIterator<E> {
1240 >        ListItr(int index) {
1241 >            super();
1242 >            cursor = index;
1243          }
1244  
1245 <        public int hashCode() {
1246 <            synchronized(base) {return super.hashCode();}
1245 >        public boolean hasPrevious() {
1246 >            return cursor != 0;
1247          }
1248  
1249 <        public int indexOf(Object o) {
1250 <            synchronized(base) {return super.indexOf(o);}
1249 >        public int nextIndex() {
1250 >            return cursor;
1251          }
1252  
1253 <        public int lastIndexOf(Object o) {
1254 <            synchronized(base) {return super.lastIndexOf(o);}
1253 >        public int previousIndex() {
1254 >            return cursor - 1;
1255          }
1256  
1257 <        public List<E> subList(int fromIndex, int toIndex) {
1258 <            return new VectorSubList(base, this, fromIndex + baseOffset,
1259 <                                     fromIndex, toIndex);
1257 >        public E previous() {
1258 >            synchronized (Vector.this) {
1259 >                checkForComodification();
1260 >                int i = cursor - 1;
1261 >                if (i < 0)
1262 >                    throw new NoSuchElementException();
1263 >                cursor = i;
1264 >                return elementData(lastRet = i);
1265 >            }
1266          }
1267  
1268 <        public Iterator<E> iterator() {
1269 <            synchronized(base) {
1270 <                return new VectorSubListIterator(this, 0);
1268 >        public void set(E e) {
1269 >            if (lastRet == -1)
1270 >                throw new IllegalStateException();
1271 >            synchronized (Vector.this) {
1272 >                checkForComodification();
1273 >                Vector.this.set(lastRet, e);
1274              }
1275          }
1276  
1277 <        public synchronized ListIterator<E> listIterator() {
1278 <            synchronized(base) {
1279 <                return new VectorSubListIterator(this, 0);
1277 >        public void add(E e) {
1278 >            int i = cursor;
1279 >            synchronized (Vector.this) {
1280 >                checkForComodification();
1281 >                Vector.this.add(i, e);
1282 >                expectedModCount = modCount;
1283              }
1284 +            cursor = i + 1;
1285 +            lastRet = -1;
1286          }
1287 +    }
1288  
1289 <        public ListIterator<E> listIterator(int index) {
1290 <            synchronized(base) {
1291 <                if (index < 0 || index > length)
1292 <                    throw indexError(index);
1293 <                return new VectorSubListIterator(this, index);
1294 <            }
1289 >    @Override
1290 >    public synchronized void forEach(Consumer<? super E> action) {
1291 >        Objects.requireNonNull(action);
1292 >        final int expectedModCount = modCount;
1293 >        @SuppressWarnings("unchecked")
1294 >        final E[] elementData = (E[]) this.elementData;
1295 >        final int elementCount = this.elementCount;
1296 >        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1297 >            action.accept(elementData[i]);
1298 >        }
1299 >        if (modCount != expectedModCount) {
1300 >            throw new ConcurrentModificationException();
1301          }
1302 +    }
1303  
1304 <        /**
1305 <         * Same idea as VectorIterator, except routing structural
1306 <         * change operations through the sublist.
1307 <         */
1308 <        private static final class VectorSubListIterator<E> implements ListIterator<E> {
1309 <            final Vector<E> base;         // base list
1310 <            final VectorSubList<E> outer; // Sublist creating this iteraor
1311 <            final int offset;             // cursor offset wrt base
1312 <            int cursor;                   // Current index
1313 <            int fence;                    // Upper bound on cursor
1314 <            int lastRet;                  // Index of returned element, or -1
1315 <            int expectedModCount;         // Expected modCount of base Vector
1316 <
1317 <            VectorSubListIterator(VectorSubList<E> list, int index) {
1318 <                this.lastRet = -1;
1319 <                this.cursor = index;
1320 <                this.outer = list;
1321 <                this.offset = list.baseOffset;
1322 <                this.fence = list.length;
1323 <                this.base = list.base;
1324 <                this.expectedModCount = base.modCount;
1304 >    @Override
1305 >    @SuppressWarnings("unchecked")
1306 >    public synchronized boolean removeIf(Predicate<? super E> filter) {
1307 >        Objects.requireNonNull(filter);
1308 >        // figure out which elements are to be removed
1309 >        // any exception thrown from the filter predicate at this stage
1310 >        // will leave the collection unmodified
1311 >        int removeCount = 0;
1312 >        final int size = elementCount;
1313 >        final BitSet removeSet = new BitSet(size);
1314 >        final int expectedModCount = modCount;
1315 >        for (int i=0; modCount == expectedModCount && i < size; i++) {
1316 >            @SuppressWarnings("unchecked")
1317 >            final E element = (E) elementData[i];
1318 >            if (filter.test(element)) {
1319 >                removeSet.set(i);
1320 >                removeCount++;
1321 >            }
1322 >        }
1323 >        if (modCount != expectedModCount) {
1324 >            throw new ConcurrentModificationException();
1325 >        }
1326 >
1327 >        // shift surviving elements left over the spaces left by removed elements
1328 >        final boolean anyToRemove = removeCount > 0;
1329 >        if (anyToRemove) {
1330 >            final int newSize = size - removeCount;
1331 >            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1332 >                i = removeSet.nextClearBit(i);
1333 >                elementData[j] = elementData[i];
1334              }
1335 <
1336 <            public boolean hasNext() {
1363 <                return cursor < fence;
1335 >            for (int k=newSize; k < size; k++) {
1336 >                elementData[k] = null;  // Let gc do its work
1337              }
1338 <
1339 <            public boolean hasPrevious() {
1340 <                return cursor > 0;
1338 >            elementCount = newSize;
1339 >            if (modCount != expectedModCount) {
1340 >                throw new ConcurrentModificationException();
1341              }
1342 +            modCount++;
1343 +        }
1344  
1345 <            public int nextIndex() {
1346 <                return cursor;
1372 <            }
1345 >        return anyToRemove;
1346 >    }
1347  
1348 <            public int previousIndex() {
1349 <                return cursor - 1;
1350 <            }
1348 >    @Override
1349 >    @SuppressWarnings("unchecked")
1350 >    public synchronized void replaceAll(UnaryOperator<E> operator) {
1351 >        Objects.requireNonNull(operator);
1352 >        final int expectedModCount = modCount;
1353 >        final int size = elementCount;
1354 >        for (int i=0; modCount == expectedModCount && i < size; i++) {
1355 >            elementData[i] = operator.apply((E) elementData[i]);
1356 >        }
1357 >        if (modCount != expectedModCount) {
1358 >            throw new ConcurrentModificationException();
1359 >        }
1360 >        modCount++;
1361 >    }
1362  
1363 <            public E next() {
1364 <                int i = cursor;
1365 <                if (cursor >= fence)
1366 <                    throw new NoSuchElementException();
1367 <                Object next = base.iteratorGet(i + offset, expectedModCount);
1368 <                lastRet = i;
1369 <                cursor = i + 1;
1370 <                return (E)next;
1371 <            }
1363 >    @SuppressWarnings("unchecked")
1364 >    @Override
1365 >    public synchronized void sort(Comparator<? super E> c) {
1366 >        final int expectedModCount = modCount;
1367 >        Arrays.sort((E[]) elementData, 0, elementCount, c);
1368 >        if (modCount != expectedModCount) {
1369 >            throw new ConcurrentModificationException();
1370 >        }
1371 >        modCount++;
1372 >    }
1373  
1374 <            public E previous() {
1375 <                int i = cursor - 1;
1376 <                if (i < 0)
1377 <                    throw new NoSuchElementException();
1378 <                Object prev = base.iteratorGet(i + offset, expectedModCount);
1379 <                lastRet = i;
1380 <                cursor = i;
1381 <                return (E)prev;
1382 <            }
1374 >    /**
1375 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1376 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1377 >     * list.
1378 >     *
1379 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1380 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1381 >     * Overriding implementations should document the reporting of additional
1382 >     * characteristic values.
1383 >     *
1384 >     * @return a {@code Spliterator} over the elements in this list
1385 >     * @since 1.8
1386 >     */
1387 >    @Override
1388 >    public Spliterator<E> spliterator() {
1389 >        return new VectorSpliterator<>(this, null, 0, -1, 0);
1390 >    }
1391 >
1392 >    /** Similar to ArrayList Spliterator */
1393 >    static final class VectorSpliterator<E> implements Spliterator<E> {
1394 >        private final Vector<E> list;
1395 >        private Object[] array;
1396 >        private int index; // current index, modified on advance/split
1397 >        private int fence; // -1 until used; then one past last index
1398 >        private int expectedModCount; // initialized when fence set
1399 >
1400 >        /** Create new spliterator covering the given  range */
1401 >        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1402 >                          int expectedModCount) {
1403 >            this.list = list;
1404 >            this.array = array;
1405 >            this.index = origin;
1406 >            this.fence = fence;
1407 >            this.expectedModCount = expectedModCount;
1408 >        }
1409  
1410 <            public void set(E e) {
1411 <                if (lastRet < 0)
1412 <                    throw new IllegalStateException();
1413 <                if (base.modCount != expectedModCount)
1414 <                    throw new ConcurrentModificationException();
1415 <                try {
1416 <                    outer.set(lastRet, e);
1405 <                    expectedModCount = base.modCount;
1406 <                } catch (IndexOutOfBoundsException ex) {
1407 <                    throw new ConcurrentModificationException();
1410 >        private int getFence() { // initialize on first use
1411 >            int hi;
1412 >            if ((hi = fence) < 0) {
1413 >                synchronized(list) {
1414 >                    array = list.elementData;
1415 >                    expectedModCount = list.modCount;
1416 >                    hi = fence = list.elementCount;
1417                  }
1418              }
1419 +            return hi;
1420 +        }
1421  
1422 <            public void remove() {
1423 <                int i = lastRet;
1424 <                if (i < 0)
1425 <                    throw new IllegalStateException();
1426 <                if (base.modCount != expectedModCount)
1427 <                    throw new ConcurrentModificationException();
1428 <                try {
1429 <                    outer.remove(i);
1430 <                    if (i < cursor)
1431 <                        cursor--;
1432 <                    lastRet = -1;
1433 <                    fence = outer.length;
1434 <                    expectedModCount = base.modCount;
1435 <                } catch (IndexOutOfBoundsException ex) {
1422 >        public Spliterator<E> trySplit() {
1423 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1424 >            return (lo >= mid) ? null :
1425 >                new VectorSpliterator<>(list, array, lo, index = mid,
1426 >                                        expectedModCount);
1427 >        }
1428 >
1429 >        @SuppressWarnings("unchecked")
1430 >        public boolean tryAdvance(Consumer<? super E> action) {
1431 >            int i;
1432 >            if (action == null)
1433 >                throw new NullPointerException();
1434 >            if (getFence() > (i = index)) {
1435 >                index = i + 1;
1436 >                action.accept((E)array[i]);
1437 >                if (list.modCount != expectedModCount)
1438                      throw new ConcurrentModificationException();
1439 <                }
1439 >                return true;
1440              }
1441 +            return false;
1442 +        }
1443  
1444 <            public void add(E e) {
1445 <                if (base.modCount != expectedModCount)
1446 <                    throw new ConcurrentModificationException();
1447 <                try {
1448 <                    int i = cursor;
1449 <                    outer.add(i, e);
1450 <                    cursor = i + 1;
1451 <                    lastRet = -1;
1452 <                    fence = outer.length;
1453 <                    expectedModCount = base.modCount;
1454 <                } catch (IndexOutOfBoundsException ex) {
1455 <                    throw new ConcurrentModificationException();
1444 >        @SuppressWarnings("unchecked")
1445 >        public void forEachRemaining(Consumer<? super E> action) {
1446 >            int i, hi; // hoist accesses and checks from loop
1447 >            Vector<E> lst; Object[] a;
1448 >            if (action == null)
1449 >                throw new NullPointerException();
1450 >            if ((lst = list) != null) {
1451 >                if ((hi = fence) < 0) {
1452 >                    synchronized(lst) {
1453 >                        expectedModCount = lst.modCount;
1454 >                        a = array = lst.elementData;
1455 >                        hi = fence = lst.elementCount;
1456 >                    }
1457 >                }
1458 >                else
1459 >                    a = array;
1460 >                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1461 >                    while (i < hi)
1462 >                        action.accept((E) a[i++]);
1463 >                    if (lst.modCount == expectedModCount)
1464 >                        return;
1465                  }
1466              }
1467 +            throw new ConcurrentModificationException();
1468          }
1444    }
1445 }
1446
1469  
1470 +        public long estimateSize() {
1471 +            return getFence() - index;
1472 +        }
1473  
1474 +        public int characteristics() {
1475 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1476 +        }
1477 +    }
1478 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines