1 /*
   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  * 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
  35  * accessed using an integer index. However, the size of a
  36  * {@code Vector} can grow or shrink as needed to accommodate
  37  * adding and removing items after the {@code Vector} has been created.
  38  *
  39  * <p>Each vector tries to optimize storage management by maintaining a
  40  * {@code capacity} and a {@code capacityIncrement}. The
  41  * {@code capacity} is always at least as large as the vector
  42  * size; it is usually larger because as components are added to the
  43  * vector, the vector's storage increases in chunks the size of
  44  * {@code capacityIncrement}. An application can increase the
  45  * capacity of a vector before inserting a large number of
  46  * components; this reduces the amount of incremental reallocation.
  47  *
  48  * <p id="fail-fast">
  49  * The iterators returned by this class's {@link #iterator() iterator} and
  50  * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
  51  * if the vector is structurally modified at any time after the iterator is
  52  * created, in any way except through the iterator's own
  53  * {@link ListIterator#remove() remove} or
  54  * {@link ListIterator#add(Object) add} methods, the iterator will throw a
  55  * {@link ConcurrentModificationException}.  Thus, in the face of
  56  * concurrent modification, the iterator fails quickly and cleanly, rather
  57  * than risking arbitrary, non-deterministic behavior at an undetermined
  58  * time in the future.  The {@link Enumeration Enumerations} returned by
  59  * the {@link #elements() elements} method are <em>not</em> fail-fast; if the
  60  * Vector is structurally modified at any time after the enumeration is
  61  * created then the results of enumerating are undefined.
  62  *
  63  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  64  * as it is, generally speaking, impossible to make any hard guarantees in the
  65  * presence of unsynchronized concurrent modification.  Fail-fast iterators
  66  * throw {@code ConcurrentModificationException} on a best-effort basis.
  67  * Therefore, it would be wrong to write a program that depended on this
  68  * exception for its correctness:  <i>the fail-fast behavior of iterators
  69  * should be used only to detect bugs.</i>
  70  *
  71  * <p>As of the Java 2 platform v1.2, this class was retrofitted to
  72  * implement the {@link List} interface, making it a member of the
  73  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  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
  83  * @see Collection
  84  * @see LinkedList
  85  * @since   1.0
  86  */
  87 public class Vector<E>
  88     extends AbstractList<E>
  89     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  90 {
  91     /**
  92      * The array buffer into which the components of the vector are
  93      * stored. The capacity of the vector is the length of this array buffer,
  94      * and is at least large enough to contain all the vector's elements.
  95      *
  96      * <p>Any array elements following the last element in the Vector are null.
  97      *
  98      * @serial
  99      */
 100     protected Object[] elementData;
 101 
 102     /**
 103      * The number of valid components in this {@code Vector} object.
 104      * Components {@code elementData[0]} through
 105      * {@code elementData[elementCount-1]} are the actual items.
 106      *
 107      * @serial
 108      */
 109     protected int elementCount;
 110 
 111     /**
 112      * The amount by which the capacity of the vector is automatically
 113      * incremented when its size becomes greater than its capacity.  If
 114      * the capacity increment is less than or equal to zero, the capacity
 115      * of the vector is doubled each time it needs to grow.
 116      *
 117      * @serial
 118      */
 119     protected int capacityIncrement;
 120 
 121     /** use serialVersionUID from JDK 1.0.2 for interoperability */
 122     private static final long serialVersionUID = -2767605614048989439L;
 123 
 124     /**
 125      * Constructs an empty vector with the specified initial capacity and
 126      * capacity increment.
 127      *
 128      * @param   initialCapacity     the initial capacity of the vector
 129      * @param   capacityIncrement   the amount by which the capacity is
 130      *                              increased when the vector overflows
 131      * @throws IllegalArgumentException if the specified initial capacity
 132      *         is negative
 133      */
 134     public Vector(int initialCapacity, int capacityIncrement) {
 135         super();
 136         if (initialCapacity < 0)
 137             throw new IllegalArgumentException("Illegal Capacity: "+
 138                                                initialCapacity);
 139         this.elementData = new Object[initialCapacity];
 140         this.capacityIncrement = capacityIncrement;
 141     }
 142 
 143     /**
 144      * Constructs an empty vector with the specified initial capacity and
 145      * with its capacity increment equal to zero.
 146      *
 147      * @param   initialCapacity   the initial capacity of the vector
 148      * @throws IllegalArgumentException if the specified initial capacity
 149      *         is negative
 150      */
 151     public Vector(int initialCapacity) {
 152         this(initialCapacity, 0);
 153     }
 154 
 155     /**
 156      * Constructs an empty vector so that its internal data array
 157      * has size {@code 10} and its standard capacity increment is
 158      * zero.
 159      */
 160     public Vector() {
 161         this(10);
 162     }
 163 
 164     /**
 165      * Constructs a vector containing the elements of the specified
 166      * collection, in the order they are returned by the collection's
 167      * iterator.
 168      *
 169      * @param c the collection whose elements are to be placed into this
 170      *       vector
 171      * @throws NullPointerException if the specified collection is null
 172      * @since   1.2
 173      */
 174     public Vector(Collection<? extends E> c) {
 175         elementData = c.toArray();
 176         elementCount = elementData.length;
 177         // defend against c.toArray (incorrectly) not returning Object[]
 178         // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
 179         if (elementData.getClass() != Object[].class)
 180             elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
 181     }
 182 
 183     /**
 184      * Copies the components of this vector into the specified array.
 185      * The item at index {@code k} in this vector is copied into
 186      * component {@code k} of {@code anArray}.
 187      *
 188      * @param  anArray the array into which the components get copied
 189      * @throws NullPointerException if the given array is null
 190      * @throws IndexOutOfBoundsException if the specified array is not
 191      *         large enough to hold all the components of this vector
 192      * @throws ArrayStoreException if a component of this vector is not of
 193      *         a runtime type that can be stored in the specified array
 194      * @see #toArray(Object[])
 195      */
 196     public synchronized void copyInto(Object[] anArray) {
 197         System.arraycopy(elementData, 0, anArray, 0, elementCount);
 198     }
 199 
 200     /**
 201      * Trims the capacity of this vector to be the vector's current
 202      * size. If the capacity of this vector is larger than its current
 203      * size, then the capacity is changed to equal the size by replacing
 204      * its internal data array, kept in the field {@code elementData},
 205      * with a smaller one. An application can use this operation to
 206      * minimize the storage of a vector.
 207      */
 208     public synchronized void trimToSize() {
 209         modCount++;
 210         int oldCapacity = elementData.length;
 211         if (elementCount < oldCapacity) {
 212             elementData = Arrays.copyOf(elementData, elementCount);
 213         }
 214     }
 215 
 216     /**
 217      * Increases the capacity of this vector, if necessary, to ensure
 218      * that it can hold at least the number of components specified by
 219      * the minimum capacity argument.
 220      *
 221      * <p>If the current capacity of this vector is less than
 222      * {@code minCapacity}, then its capacity is increased by replacing its
 223      * internal data array, kept in the field {@code elementData}, with a
 224      * larger one.  The size of the new data array will be the old size plus
 225      * {@code capacityIncrement}, unless the value of
 226      * {@code capacityIncrement} is less than or equal to zero, in which case
 227      * the new capacity will be twice the old capacity; but if this new size
 228      * is still smaller than {@code minCapacity}, then the new capacity will
 229      * be {@code minCapacity}.
 230      *
 231      * @param minCapacity the desired minimum capacity
 232      */
 233     public synchronized void ensureCapacity(int minCapacity) {
 234         if (minCapacity > 0) {
 235             modCount++;
 236             ensureCapacityHelper(minCapacity);
 237         }
 238     }
 239 
 240     /**
 241      * This implements the unsynchronized semantics of ensureCapacity.
 242      * Synchronized methods in this class can internally call this
 243      * method for ensuring capacity without incurring the cost of an
 244      * extra synchronization.
 245      *
 246      * @see #ensureCapacity(int)
 247      */
 248     private void ensureCapacityHelper(int minCapacity) {
 249         // overflow-conscious code
 250         if (minCapacity - elementData.length > 0)
 251             grow(minCapacity);
 252     }
 253 
 254     /**
 255      * The maximum size of array to allocate.
 256      * Some VMs reserve some header words in an array.
 257      * Attempts to allocate larger arrays may result in
 258      * OutOfMemoryError: Requested array size exceeds VM limit
 259      */
 260     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 261 
 262     private void grow(int minCapacity) {
 263         // overflow-conscious code
 264         int oldCapacity = elementData.length;
 265         int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
 266                                          capacityIncrement : oldCapacity);
 267         if (newCapacity - minCapacity < 0)
 268             newCapacity = minCapacity;
 269         if (newCapacity - MAX_ARRAY_SIZE > 0)
 270             newCapacity = hugeCapacity(minCapacity);
 271         elementData = Arrays.copyOf(elementData, newCapacity);
 272     }
 273 
 274     private static int hugeCapacity(int minCapacity) {
 275         if (minCapacity < 0) // overflow
 276             throw new OutOfMemoryError();
 277         return (minCapacity > MAX_ARRAY_SIZE) ?
 278             Integer.MAX_VALUE :
 279             MAX_ARRAY_SIZE;
 280     }
 281 
 282     /**
 283      * Sets the size of this vector. If the new size is greater than the
 284      * current size, new {@code null} items are added to the end of
 285      * the vector. If the new size is less than the current size, all
 286      * components at index {@code newSize} and greater are discarded.
 287      *
 288      * @param  newSize   the new size of this vector
 289      * @throws ArrayIndexOutOfBoundsException if the new size is negative
 290      */
 291     public synchronized void setSize(int newSize) {
 292         modCount++;
 293         if (newSize > elementCount) {
 294             ensureCapacityHelper(newSize);
 295         } else {
 296             for (int i = newSize ; i < elementCount ; i++) {
 297                 elementData[i] = null;
 298             }
 299         }
 300         elementCount = newSize;
 301     }
 302 
 303     /**
 304      * Returns the current capacity of this vector.
 305      *
 306      * @return  the current capacity (the length of its internal
 307      *          data array, kept in the field {@code elementData}
 308      *          of this vector)
 309      */
 310     public synchronized int capacity() {
 311         return elementData.length;
 312     }
 313 
 314     /**
 315      * Returns the number of components in this vector.
 316      *
 317      * @return  the number of components in this vector
 318      */
 319     public synchronized int size() {
 320         return elementCount;
 321     }
 322 
 323     /**
 324      * Tests if this vector has no components.
 325      *
 326      * @return  {@code true} if and only if this vector has
 327      *          no components, that is, its size is zero;
 328      *          {@code false} otherwise.
 329      */
 330     public synchronized boolean isEmpty() {
 331         return elementCount == 0;
 332     }
 333 
 334     /**
 335      * Returns an enumeration of the components of this vector. The
 336      * returned {@code Enumeration} object will generate all items in
 337      * this vector. The first item generated is the item at index {@code 0},
 338      * then the item at index {@code 1}, and so on. If the vector is
 339      * structurally modified while enumerating over the elements then the
 340      * results of enumerating are undefined.
 341      *
 342      * @return  an enumeration of the components of this vector
 343      * @see     Iterator
 344      */
 345     public Enumeration<E> elements() {
 346         return new Enumeration<E>() {
 347             int count = 0;
 348 
 349             public boolean hasMoreElements() {
 350                 return count < elementCount;
 351             }
 352 
 353             public E nextElement() {
 354                 synchronized (Vector.this) {
 355                     if (count < elementCount) {
 356                         return elementData(count++);
 357                     }
 358                 }
 359                 throw new NoSuchElementException("Vector Enumeration");
 360             }
 361         };
 362     }
 363 
 364     /**
 365      * Returns {@code true} if this vector contains the specified element.
 366      * More formally, returns {@code true} if and only if this vector
 367      * contains at least one element {@code e} such that
 368      * <code>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</code>.
 369      *
 370      * @param o element whose presence in this vector is to be tested
 371      * @return {@code true} if this vector contains the specified element
 372      */
 373     public boolean contains(Object o) {
 374         return indexOf(o, 0) >= 0;
 375     }
 376 
 377     /**
 378      * Returns the index of the first occurrence of the specified element
 379      * in this vector, or -1 if this vector does not contain the element.
 380      * More formally, returns the lowest index {@code i} such that
 381      * <code>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</code>,
 382      * or -1 if there is no such index.
 383      *
 384      * @param o element to search for
 385      * @return the index of the first occurrence of the specified element in
 386      *         this vector, or -1 if this vector does not contain the element
 387      */
 388     public int indexOf(Object o) {
 389         return indexOf(o, 0);
 390     }
 391 
 392     /**
 393      * Returns the index of the first occurrence of the specified element in
 394      * this vector, searching forwards from {@code index}, or returns -1 if
 395      * the element is not found.
 396      * More formally, returns the lowest index {@code i} such that
 397      * <code>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</code>,
 398      * or -1 if there is no such index.
 399      *
 400      * @param o element to search for
 401      * @param index index to start searching from
 402      * @return the index of the first occurrence of the element in
 403      *         this vector at position {@code index} or later in the vector;
 404      *         {@code -1} if the element is not found.
 405      * @throws IndexOutOfBoundsException if the specified index is negative
 406      * @see     Object#equals(Object)
 407      */
 408     public synchronized int indexOf(Object o, int index) {
 409         if (o == null) {
 410             for (int i = index ; i < elementCount ; i++)
 411                 if (elementData[i]==null)
 412                     return i;
 413         } else {
 414             for (int i = index ; i < elementCount ; i++)
 415                 if (o.equals(elementData[i]))
 416                     return i;
 417         }
 418         return -1;
 419     }
 420 
 421     /**
 422      * Returns the index of the last occurrence of the specified element
 423      * in this vector, or -1 if this vector does not contain the element.
 424      * More formally, returns the highest index {@code i} such that
 425      * <code>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</code>,
 426      * or -1 if there is no such index.
 427      *
 428      * @param o element to search for
 429      * @return the index of the last occurrence of the specified element in
 430      *         this vector, or -1 if this vector does not contain the element
 431      */
 432     public synchronized int lastIndexOf(Object o) {
 433         return lastIndexOf(o, elementCount-1);
 434     }
 435 
 436     /**
 437      * Returns the index of the last occurrence of the specified element in
 438      * this vector, searching backwards from {@code index}, or returns -1 if
 439      * the element is not found.
 440      * More formally, returns the highest index {@code i} such that
 441      * <code>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</code>,
 442      * or -1 if there is no such index.
 443      *
 444      * @param o element to search for
 445      * @param index index to start searching backwards from
 446      * @return the index of the last occurrence of the element at position
 447      *         less than or equal to {@code index} in this vector;
 448      *         -1 if the element is not found.
 449      * @throws IndexOutOfBoundsException if the specified index is greater
 450      *         than or equal to the current size of this vector
 451      */
 452     public synchronized int lastIndexOf(Object o, int index) {
 453         if (index >= elementCount)
 454             throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
 455 
 456         if (o == null) {
 457             for (int i = index; i >= 0; i--)
 458                 if (elementData[i]==null)
 459                     return i;
 460         } else {
 461             for (int i = index; i >= 0; i--)
 462                 if (o.equals(elementData[i]))
 463                     return i;
 464         }
 465         return -1;
 466     }
 467 
 468     /**
 469      * Returns the component at the specified index.
 470      *
 471      * <p>This method is identical in functionality to the {@link #get(int)}
 472      * method (which is part of the {@link List} interface).
 473      *
 474      * @param      index   an index into this vector
 475      * @return     the component at the specified index
 476      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 477      *         ({@code index < 0 || index >= size()})
 478      */
 479     public synchronized E elementAt(int index) {
 480         if (index >= elementCount) {
 481             throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
 482         }
 483 
 484         return elementData(index);
 485     }
 486 
 487     /**
 488      * Returns the first component (the item at index {@code 0}) of
 489      * this vector.
 490      *
 491      * @return     the first component of this vector
 492      * @throws NoSuchElementException if this vector has no components
 493      */
 494     public synchronized E firstElement() {
 495         if (elementCount == 0) {
 496             throw new NoSuchElementException();
 497         }
 498         return elementData(0);
 499     }
 500 
 501     /**
 502      * Returns the last component of the vector.
 503      *
 504      * @return  the last component of the vector, i.e., the component at index
 505      *          <code>size()&nbsp;-&nbsp;1</code>.
 506      * @throws NoSuchElementException if this vector is empty
 507      */
 508     public synchronized E lastElement() {
 509         if (elementCount == 0) {
 510             throw new NoSuchElementException();
 511         }
 512         return elementData(elementCount - 1);
 513     }
 514 
 515     /**
 516      * Sets the component at the specified {@code index} of this
 517      * vector to be the specified object. The previous component at that
 518      * position is discarded.
 519      *
 520      * <p>The index must be a value greater than or equal to {@code 0}
 521      * and less than the current size of the vector.
 522      *
 523      * <p>This method is identical in functionality to the
 524      * {@link #set(int, Object) set(int, E)}
 525      * method (which is part of the {@link List} interface). Note that the
 526      * {@code set} method reverses the order of the parameters, to more closely
 527      * match array usage.  Note also that the {@code set} method returns the
 528      * old value that was stored at the specified position.
 529      *
 530      * @param      obj     what the component is to be set to
 531      * @param      index   the specified index
 532      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 533      *         ({@code index < 0 || index >= size()})
 534      */
 535     public synchronized void setElementAt(E obj, int index) {
 536         if (index >= elementCount) {
 537             throw new ArrayIndexOutOfBoundsException(index + " >= " +
 538                                                      elementCount);
 539         }
 540         elementData[index] = obj;
 541     }
 542 
 543     /**
 544      * Deletes the component at the specified index. Each component in
 545      * this vector with an index greater or equal to the specified
 546      * {@code index} is shifted downward to have an index one
 547      * smaller than the value it had previously. The size of this vector
 548      * is decreased by {@code 1}.
 549      *
 550      * <p>The index must be a value greater than or equal to {@code 0}
 551      * and less than the current size of the vector.
 552      *
 553      * <p>This method is identical in functionality to the {@link #remove(int)}
 554      * method (which is part of the {@link List} interface).  Note that the
 555      * {@code remove} method returns the old value that was stored at the
 556      * specified position.
 557      *
 558      * @param      index   the index of the object to remove
 559      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 560      *         ({@code index < 0 || index >= size()})
 561      */
 562     public synchronized void removeElementAt(int index) {
 563         if (index >= elementCount) {
 564             throw new ArrayIndexOutOfBoundsException(index + " >= " +
 565                                                      elementCount);
 566         }
 567         else if (index < 0) {
 568             throw new ArrayIndexOutOfBoundsException(index);
 569         }
 570         int j = elementCount - index - 1;
 571         if (j > 0) {
 572             System.arraycopy(elementData, index + 1, elementData, index, j);
 573         }
 574         modCount++;
 575         elementCount--;
 576         elementData[elementCount] = null; /* to let gc do its work */
 577     }
 578 
 579     /**
 580      * Inserts the specified object as a component in this vector at the
 581      * specified {@code index}. Each component in this vector with
 582      * an index greater or equal to the specified {@code index} is
 583      * shifted upward to have an index one greater than the value it had
 584      * previously.
 585      *
 586      * <p>The index must be a value greater than or equal to {@code 0}
 587      * and less than or equal to the current size of the vector. (If the
 588      * index is equal to the current size of the vector, the new element
 589      * is appended to the Vector.)
 590      *
 591      * <p>This method is identical in functionality to the
 592      * {@link #add(int, Object) add(int, E)}
 593      * method (which is part of the {@link List} interface).  Note that the
 594      * {@code add} method reverses the order of the parameters, to more closely
 595      * match array usage.
 596      *
 597      * @param      obj     the component to insert
 598      * @param      index   where to insert the new component
 599      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 600      *         ({@code index < 0 || index > size()})
 601      */
 602     public synchronized void insertElementAt(E obj, int index) {
 603         if (index > elementCount) {
 604             throw new ArrayIndexOutOfBoundsException(index
 605                                                      + " > " + elementCount);
 606         }
 607         ensureCapacityHelper(elementCount + 1);
 608         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
 609         elementData[index] = obj;
 610         modCount++;
 611         elementCount++;
 612     }
 613 
 614     /**
 615      * Adds the specified component to the end of this vector,
 616      * increasing its size by one. The capacity of this vector is
 617      * increased if its size becomes greater than its capacity.
 618      *
 619      * <p>This method is identical in functionality to the
 620      * {@link #add(Object) add(E)}
 621      * method (which is part of the {@link List} interface).
 622      *
 623      * @param   obj   the component to be added
 624      */
 625     public synchronized void addElement(E obj) {
 626         ensureCapacityHelper(elementCount + 1);
 627         modCount++;
 628         elementData[elementCount++] = obj;
 629     }
 630 
 631     /**
 632      * Removes the first (lowest-indexed) occurrence of the argument
 633      * from this vector. If the object is found in this vector, each
 634      * component in the vector with an index greater or equal to the
 635      * object's index is shifted downward to have an index one smaller
 636      * than the value it had previously.
 637      *
 638      * <p>This method is identical in functionality to the
 639      * {@link #remove(Object)} method (which is part of the
 640      * {@link List} interface).
 641      *
 642      * @param   obj   the component to be removed
 643      * @return  {@code true} if the argument was a component of this
 644      *          vector; {@code false} otherwise.
 645      */
 646     public synchronized boolean removeElement(Object obj) {
 647         modCount++;
 648         int i = indexOf(obj);
 649         if (i >= 0) {
 650             removeElementAt(i);
 651             return true;
 652         }
 653         return false;
 654     }
 655 
 656     /**
 657      * Removes all components from this vector and sets its size to zero.
 658      *
 659      * <p>This method is identical in functionality to the {@link #clear}
 660      * method (which is part of the {@link List} interface).
 661      */
 662     public synchronized void removeAllElements() {
 663         // Let gc do its work
 664         for (int i = 0; i < elementCount; i++)
 665             elementData[i] = null;
 666 
 667         modCount++;
 668         elementCount = 0;
 669     }
 670 
 671     /**
 672      * Returns a clone of this vector. The copy will contain a
 673      * reference to a clone of the internal data array, not a reference
 674      * to the original internal data array of this {@code Vector} object.
 675      *
 676      * @return  a clone of this vector
 677      */
 678     public synchronized Object clone() {
 679         try {
 680             @SuppressWarnings("unchecked")
 681                 Vector<E> v = (Vector<E>) super.clone();
 682             v.elementData = Arrays.copyOf(elementData, elementCount);
 683             v.modCount = 0;
 684             return v;
 685         } catch (CloneNotSupportedException e) {
 686             // this shouldn't happen, since we are Cloneable
 687             throw new InternalError(e);
 688         }
 689     }
 690 
 691     /**
 692      * Returns an array containing all of the elements in this Vector
 693      * in the correct order.
 694      *
 695      * @since 1.2
 696      */
 697     public synchronized Object[] toArray() {
 698         return Arrays.copyOf(elementData, elementCount);
 699     }
 700 
 701     /**
 702      * Returns an array containing all of the elements in this Vector in the
 703      * correct order; the runtime type of the returned array is that of the
 704      * specified array.  If the Vector fits in the specified array, it is
 705      * returned therein.  Otherwise, a new array is allocated with the runtime
 706      * type of the specified array and the size of this Vector.
 707      *
 708      * <p>If the Vector fits in the specified array with room to spare
 709      * (i.e., the array has more elements than the Vector),
 710      * the element in the array immediately following the end of the
 711      * Vector is set to null.  (This is useful in determining the length
 712      * of the Vector <em>only</em> if the caller knows that the Vector
 713      * does not contain any null elements.)
 714      *
 715      * @param <T> type of array elements. The same type as {@code <E>} or a
 716      * supertype of {@code <E>}.
 717      * @param a the array into which the elements of the Vector are to
 718      *          be stored, if it is big enough; otherwise, a new array of the
 719      *          same runtime type is allocated for this purpose.
 720      * @return an array containing the elements of the Vector
 721      * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
 722      * a supertype of the runtime type, {@code <E>}, of every element in this
 723      * Vector
 724      * @throws NullPointerException if the given array is null
 725      * @since 1.2
 726      */
 727     @SuppressWarnings("unchecked")
 728     public synchronized <T> T[] toArray(T[] a) {
 729         if (a.length < elementCount)
 730             return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
 731 
 732         System.arraycopy(elementData, 0, a, 0, elementCount);
 733 
 734         if (a.length > elementCount)
 735             a[elementCount] = null;
 736 
 737         return a;
 738     }
 739 
 740     // Positional Access Operations
 741 
 742     @SuppressWarnings("unchecked")
 743     E elementData(int index) {
 744         return (E) elementData[index];
 745     }
 746 
 747     /**
 748      * Returns the element at the specified position in this Vector.
 749      *
 750      * @param index index of the element to return
 751      * @return object at the specified index
 752      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 753      *            ({@code index < 0 || index >= size()})
 754      * @since 1.2
 755      */
 756     public synchronized E get(int index) {
 757         if (index >= elementCount)
 758             throw new ArrayIndexOutOfBoundsException(index);
 759 
 760         return elementData(index);
 761     }
 762 
 763     /**
 764      * Replaces the element at the specified position in this Vector with the
 765      * specified element.
 766      *
 767      * @param index index of the element to replace
 768      * @param element element to be stored at the specified position
 769      * @return the element previously at the specified position
 770      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 771      *         ({@code index < 0 || index >= size()})
 772      * @since 1.2
 773      */
 774     public synchronized E set(int index, E element) {
 775         if (index >= elementCount)
 776             throw new ArrayIndexOutOfBoundsException(index);
 777 
 778         E oldValue = elementData(index);
 779         elementData[index] = element;
 780         return oldValue;
 781     }
 782 
 783     /**
 784      * Appends the specified element to the end of this Vector.
 785      *
 786      * @param e element to be appended to this Vector
 787      * @return {@code true} (as specified by {@link Collection#add})
 788      * @since 1.2
 789      */
 790     public synchronized boolean add(E e) {
 791         ensureCapacityHelper(elementCount + 1);
 792         modCount++;
 793         elementData[elementCount++] = e;
 794         return true;
 795     }
 796 
 797     /**
 798      * Removes the first occurrence of the specified element in this Vector
 799      * If the Vector does not contain the element, it is unchanged.  More
 800      * formally, removes the element with the lowest index i such that
 801      * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
 802      * an element exists).
 803      *
 804      * @param o element to be removed from this Vector, if present
 805      * @return true if the Vector contained the specified element
 806      * @since 1.2
 807      */
 808     public boolean remove(Object o) {
 809         return removeElement(o);
 810     }
 811 
 812     /**
 813      * Inserts the specified element at the specified position in this Vector.
 814      * Shifts the element currently at that position (if any) and any
 815      * subsequent elements to the right (adds one to their indices).
 816      *
 817      * @param index index at which the specified element is to be inserted
 818      * @param element element to be inserted
 819      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 820      *         ({@code index < 0 || index > size()})
 821      * @since 1.2
 822      */
 823     public void add(int index, E element) {
 824         insertElementAt(element, index);
 825     }
 826 
 827     /**
 828      * Removes the element at the specified position in this Vector.
 829      * Shifts any subsequent elements to the left (subtracts one from their
 830      * indices).  Returns the element that was removed from the Vector.
 831      *
 832      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 833      *         ({@code index < 0 || index >= size()})
 834      * @param index the index of the element to be removed
 835      * @return element that was removed
 836      * @since 1.2
 837      */
 838     public synchronized E remove(int index) {
 839         modCount++;
 840         if (index >= elementCount)
 841             throw new ArrayIndexOutOfBoundsException(index);
 842         E oldValue = elementData(index);
 843 
 844         int numMoved = elementCount - index - 1;
 845         if (numMoved > 0)
 846             System.arraycopy(elementData, index+1, elementData, index,
 847                              numMoved);
 848         elementData[--elementCount] = null; // Let gc do its work
 849 
 850         return oldValue;
 851     }
 852 
 853     /**
 854      * Removes all of the elements from this Vector.  The Vector will
 855      * be empty after this call returns (unless it throws an exception).
 856      *
 857      * @since 1.2
 858      */
 859     public void clear() {
 860         removeAllElements();
 861     }
 862 
 863     // Bulk Operations
 864 
 865     /**
 866      * Returns true if this Vector contains all of the elements in the
 867      * specified Collection.
 868      *
 869      * @param   c a collection whose elements will be tested for containment
 870      *          in this Vector
 871      * @return true if this Vector contains all of the elements in the
 872      *         specified collection
 873      * @throws NullPointerException if the specified collection is null
 874      */
 875     public synchronized boolean containsAll(Collection<?> c) {
 876         return super.containsAll(c);
 877     }
 878 
 879     /**
 880      * Appends all of the elements in the specified Collection to the end of
 881      * this Vector, in the order that they are returned by the specified
 882      * Collection's Iterator.  The behavior of this operation is undefined if
 883      * the specified Collection is modified while the operation is in progress.
 884      * (This implies that the behavior of this call is undefined if the
 885      * specified Collection is this Vector, and this Vector is nonempty.)
 886      *
 887      * @param c elements to be inserted into this Vector
 888      * @return {@code true} if this Vector changed as a result of the call
 889      * @throws NullPointerException if the specified collection is null
 890      * @since 1.2
 891      */
 892     public boolean addAll(Collection<? extends E> c) {
 893         Object[] a = c.toArray();
 894         int numNew = a.length;
 895         if (numNew > 0) {
 896             synchronized (this) {
 897                 ensureCapacityHelper(elementCount + numNew);
 898                 System.arraycopy(a, 0, elementData, elementCount, numNew);
 899                 modCount++;
 900                 elementCount += numNew;
 901             }
 902         }
 903         return numNew > 0;
 904     }
 905 
 906     /**
 907      * Removes from this Vector all of its elements that are contained in the
 908      * specified Collection.
 909      *
 910      * @param c a collection of elements to be removed from the Vector
 911      * @return true if this Vector changed as a result of the call
 912      * @throws ClassCastException if the types of one or more elements
 913      *         in this vector are incompatible with the specified
 914      *         collection
 915      * (<a href="Collection.html#optional-restrictions">optional</a>)
 916      * @throws NullPointerException if this vector contains one or more null
 917      *         elements and the specified collection does not support null
 918      *         elements
 919      * (<a href="Collection.html#optional-restrictions">optional</a>),
 920      *         or if the specified collection is null
 921      * @since 1.2
 922      */
 923     public synchronized boolean removeAll(Collection<?> c) {
 924         return super.removeAll(c);
 925     }
 926 
 927     /**
 928      * Retains only the elements in this Vector that are contained in the
 929      * specified Collection.  In other words, removes from this Vector all
 930      * of its elements that are not contained in the specified Collection.
 931      *
 932      * @param c a collection of elements to be retained in this Vector
 933      *          (all other elements are removed)
 934      * @return true if this Vector changed as a result of the call
 935      * @throws ClassCastException if the types of one or more elements
 936      *         in this vector are incompatible with the specified
 937      *         collection
 938      * (<a href="Collection.html#optional-restrictions">optional</a>)
 939      * @throws NullPointerException if this vector contains one or more null
 940      *         elements and the specified collection does not support null
 941      *         elements
 942      *         (<a href="Collection.html#optional-restrictions">optional</a>),
 943      *         or if the specified collection is null
 944      * @since 1.2
 945      */
 946     public synchronized boolean retainAll(Collection<?> c) {
 947         return super.retainAll(c);
 948     }
 949 
 950     /**
 951      * Inserts all of the elements in the specified Collection into this
 952      * Vector at the specified position.  Shifts the element currently at
 953      * that position (if any) and any subsequent elements to the right
 954      * (increases their indices).  The new elements will appear in the Vector
 955      * in the order that they are returned by the specified Collection's
 956      * iterator.
 957      *
 958      * @param index index at which to insert the first element from the
 959      *              specified collection
 960      * @param c elements to be inserted into this Vector
 961      * @return {@code true} if this Vector changed as a result of the call
 962      * @throws ArrayIndexOutOfBoundsException if the index is out of range
 963      *         ({@code index < 0 || index > size()})
 964      * @throws NullPointerException if the specified collection is null
 965      * @since 1.2
 966      */
 967     public synchronized boolean addAll(int index, Collection<? extends E> c) {
 968         if (index < 0 || index > elementCount)
 969             throw new ArrayIndexOutOfBoundsException(index);
 970 
 971         Object[] a = c.toArray();
 972         int numNew = a.length;
 973 
 974         if (numNew > 0) {
 975             ensureCapacityHelper(elementCount + numNew);
 976 
 977             int numMoved = elementCount - index;
 978             if (numMoved > 0)
 979                 System.arraycopy(elementData, index, elementData,
 980                         index + numNew, numMoved);
 981 
 982              System.arraycopy(a, 0, elementData, index, numNew);
 983              elementCount += numNew;
 984              modCount++;
 985         }
 986         return numNew > 0;
 987     }
 988 
 989     /**
 990      * Compares the specified Object with this Vector for equality.  Returns
 991      * true if and only if the specified Object is also a List, both Lists
 992      * have the same size, and all corresponding pairs of elements in the two
 993      * Lists are <em>equal</em>.  (Two elements {@code e1} and
 994      * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
 995      * e1.equals(e2))}.)  In other words, two Lists are defined to be
 996      * equal if they contain the same elements in the same order.
 997      *
 998      * @param o the Object to be compared for equality with this Vector
 999      * @return true if the specified Object is equal to this Vector
1000      */
1001     public synchronized boolean equals(Object o) {
1002         return super.equals(o);
1003     }
1004 
1005     /**
1006      * Returns the hash code value for this Vector.
1007      */
1008     public synchronized int hashCode() {
1009         return super.hashCode();
1010     }
1011 
1012     /**
1013      * Returns a string representation of this Vector, containing
1014      * the String representation of each element.
1015      */
1016     public synchronized String toString() {
1017         return super.toString();
1018     }
1019 
1020     /**
1021      * Returns a view of the portion of this List between fromIndex,
1022      * inclusive, and toIndex, exclusive.  (If fromIndex and toIndex are
1023      * equal, the returned List is empty.)  The returned List is backed by this
1024      * List, so changes in the returned List are reflected in this List, and
1025      * vice-versa.  The returned List supports all of the optional List
1026      * operations supported by this List.
1027      *
1028      * <p>This method eliminates the need for explicit range operations (of
1029      * the sort that commonly exist for arrays).  Any operation that expects
1030      * a List can be used as a range operation by operating on a subList view
1031      * instead of a whole List.  For example, the following idiom
1032      * removes a range of elements from a List:
1033      * <pre>
1034      *      list.subList(from, to).clear();
1035      * </pre>
1036      * Similar idioms may be constructed for indexOf and lastIndexOf,
1037      * and all of the algorithms in the Collections class can be applied to
1038      * a subList.
1039      *
1040      * <p>The semantics of the List returned by this method become undefined if
1041      * the backing list (i.e., this List) is <i>structurally modified</i> in
1042      * any way other than via the returned List.  (Structural modifications are
1043      * those that change the size of the List, or otherwise perturb it in such
1044      * a fashion that iterations in progress may yield incorrect results.)
1045      *
1046      * @param fromIndex low endpoint (inclusive) of the subList
1047      * @param toIndex high endpoint (exclusive) of the subList
1048      * @return a view of the specified range within this List
1049      * @throws IndexOutOfBoundsException if an endpoint index value is out of range
1050      *         {@code (fromIndex < 0 || toIndex > size)}
1051      * @throws IllegalArgumentException if the endpoint indices are out of order
1052      *         {@code (fromIndex > toIndex)}
1053      */
1054     public synchronized List<E> subList(int fromIndex, int toIndex) {
1055         return Collections.synchronizedList(super.subList(fromIndex, toIndex),
1056                                             this);
1057     }
1058 
1059     /**
1060      * Removes from this list all of the elements whose index is between
1061      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1062      * Shifts any succeeding elements to the left (reduces their index).
1063      * This call shortens the list by {@code (toIndex - fromIndex)} elements.
1064      * (If {@code toIndex==fromIndex}, this operation has no effect.)
1065      */
1066     protected synchronized void removeRange(int fromIndex, int toIndex) {
1067         int numMoved = elementCount - toIndex;
1068         System.arraycopy(elementData, toIndex, elementData, fromIndex,
1069                          numMoved);
1070 
1071         // Let gc do its work
1072         modCount++;
1073         int newElementCount = elementCount - (toIndex-fromIndex);
1074         while (elementCount != newElementCount)
1075             elementData[--elementCount] = null;
1076     }
1077 
1078     /**
1079      * Save the state of the {@code Vector} instance to a stream (that
1080      * is, serialize it).
1081      * This method performs synchronization to ensure the consistency
1082      * of the serialized data.
1083      */
1084     private void writeObject(java.io.ObjectOutputStream s)
1085             throws java.io.IOException {
1086         final java.io.ObjectOutputStream.PutField fields = s.putFields();
1087         final Object[] data;
1088         synchronized (this) {
1089             fields.put("capacityIncrement", capacityIncrement);
1090             fields.put("elementCount", elementCount);
1091             data = elementData.clone();
1092         }
1093         fields.put("elementData", data);
1094         s.writeFields();
1095     }
1096 
1097     /**
1098      * Returns a list iterator over the elements in this list (in proper
1099      * sequence), starting at the specified position in the list.
1100      * The specified index indicates the first element that would be
1101      * returned by an initial call to {@link ListIterator#next next}.
1102      * An initial call to {@link ListIterator#previous previous} would
1103      * return the element with the specified index minus one.
1104      *
1105      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1106      *
1107      * @throws IndexOutOfBoundsException {@inheritDoc}
1108      */
1109     public synchronized ListIterator<E> listIterator(int index) {
1110         if (index < 0 || index > elementCount)
1111             throw new IndexOutOfBoundsException("Index: "+index);
1112         return new ListItr(index);
1113     }
1114 
1115     /**
1116      * Returns a list iterator over the elements in this list (in proper
1117      * sequence).
1118      *
1119      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1120      *
1121      * @see #listIterator(int)
1122      */
1123     public synchronized ListIterator<E> listIterator() {
1124         return new ListItr(0);
1125     }
1126 
1127     /**
1128      * Returns an iterator over the elements in this list in proper sequence.
1129      *
1130      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
1131      *
1132      * @return an iterator over the elements in this list in proper sequence
1133      */
1134     public synchronized Iterator<E> iterator() {
1135         return new Itr();
1136     }
1137 
1138     /**
1139      * An optimized version of AbstractList.Itr
1140      */
1141     private class Itr implements Iterator<E> {
1142         int cursor;       // index of next element to return
1143         int lastRet = -1; // index of last element returned; -1 if no such
1144         int expectedModCount = modCount;
1145 
1146         public boolean hasNext() {
1147             // Racy but within spec, since modifications are checked
1148             // within or after synchronization in next/previous
1149             return cursor != elementCount;
1150         }
1151 
1152         public E next() {
1153             synchronized (Vector.this) {
1154                 checkForComodification();
1155                 int i = cursor;
1156                 if (i >= elementCount)
1157                     throw new NoSuchElementException();
1158                 cursor = i + 1;
1159                 return elementData(lastRet = i);
1160             }
1161         }
1162 
1163         public void remove() {
1164             if (lastRet == -1)
1165                 throw new IllegalStateException();
1166             synchronized (Vector.this) {
1167                 checkForComodification();
1168                 Vector.this.remove(lastRet);
1169                 expectedModCount = modCount;
1170             }
1171             cursor = lastRet;
1172             lastRet = -1;
1173         }
1174 
1175         @Override
1176         public void forEachRemaining(Consumer<? super E> action) {
1177             Objects.requireNonNull(action);
1178             synchronized (Vector.this) {
1179                 final int size = elementCount;
1180                 int i = cursor;
1181                 if (i >= size) {
1182                     return;
1183                 }
1184         @SuppressWarnings("unchecked")
1185                 final E[] elementData = (E[]) Vector.this.elementData;
1186                 if (i >= elementData.length) {
1187                     throw new ConcurrentModificationException();
1188                 }
1189                 while (i != size && modCount == expectedModCount) {
1190                     action.accept(elementData[i++]);
1191                 }
1192                 // update once at end of iteration to reduce heap write traffic
1193                 cursor = i;
1194                 lastRet = i - 1;
1195                 checkForComodification();
1196             }
1197         }
1198 
1199         final void checkForComodification() {
1200             if (modCount != expectedModCount)
1201                 throw new ConcurrentModificationException();
1202         }
1203     }
1204 
1205     /**
1206      * An optimized version of AbstractList.ListItr
1207      */
1208     final class ListItr extends Itr implements ListIterator<E> {
1209         ListItr(int index) {
1210             super();
1211             cursor = index;
1212         }
1213 
1214         public boolean hasPrevious() {
1215             return cursor != 0;
1216         }
1217 
1218         public int nextIndex() {
1219             return cursor;
1220         }
1221 
1222         public int previousIndex() {
1223             return cursor - 1;
1224         }
1225 
1226         public E previous() {
1227             synchronized (Vector.this) {
1228                 checkForComodification();
1229                 int i = cursor - 1;
1230                 if (i < 0)
1231                     throw new NoSuchElementException();
1232                 cursor = i;
1233                 return elementData(lastRet = i);
1234             }
1235         }
1236 
1237         public void set(E e) {
1238             if (lastRet == -1)
1239                 throw new IllegalStateException();
1240             synchronized (Vector.this) {
1241                 checkForComodification();
1242                 Vector.this.set(lastRet, e);
1243             }
1244         }
1245 
1246         public void add(E e) {
1247             int i = cursor;
1248             synchronized (Vector.this) {
1249                 checkForComodification();
1250                 Vector.this.add(i, e);
1251                 expectedModCount = modCount;
1252             }
1253             cursor = i + 1;
1254             lastRet = -1;
1255         }
1256     }
1257 
1258     @Override
1259     public synchronized void forEach(Consumer<? super E> action) {
1260         Objects.requireNonNull(action);
1261         final int expectedModCount = modCount;
1262         @SuppressWarnings("unchecked")
1263         final E[] elementData = (E[]) this.elementData;
1264         final int elementCount = this.elementCount;
1265         for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1266             action.accept(elementData[i]);
1267         }
1268         if (modCount != expectedModCount) {
1269             throw new ConcurrentModificationException();
1270         }
1271     }
1272 
1273     @Override
1274     @SuppressWarnings("unchecked")
1275     public synchronized boolean removeIf(Predicate<? super E> filter) {
1276         Objects.requireNonNull(filter);
1277         // figure out which elements are to be removed
1278         // any exception thrown from the filter predicate at this stage
1279         // will leave the collection unmodified
1280         int removeCount = 0;
1281         final int size = elementCount;
1282         final BitSet removeSet = new BitSet(size);
1283         final int expectedModCount = modCount;
1284         for (int i=0; modCount == expectedModCount && i < size; i++) {
1285             @SuppressWarnings("unchecked")
1286             final E element = (E) elementData[i];
1287             if (filter.test(element)) {
1288                 removeSet.set(i);
1289                 removeCount++;
1290             }
1291         }
1292         if (modCount != expectedModCount) {
1293             throw new ConcurrentModificationException();
1294         }
1295 
1296         // shift surviving elements left over the spaces left by removed elements
1297         final boolean anyToRemove = removeCount > 0;
1298         if (anyToRemove) {
1299             final int newSize = size - removeCount;
1300             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1301                 i = removeSet.nextClearBit(i);
1302                 elementData[j] = elementData[i];
1303             }
1304             for (int k=newSize; k < size; k++) {
1305                 elementData[k] = null;  // Let gc do its work
1306             }
1307             elementCount = newSize;
1308             if (modCount != expectedModCount) {
1309                 throw new ConcurrentModificationException();
1310             }
1311             modCount++;
1312         }
1313 
1314         return anyToRemove;
1315     }
1316 
1317     @Override
1318     @SuppressWarnings("unchecked")
1319     public synchronized void replaceAll(UnaryOperator<E> operator) {
1320         Objects.requireNonNull(operator);
1321         final int expectedModCount = modCount;
1322         final int size = elementCount;
1323         for (int i=0; modCount == expectedModCount && i < size; i++) {
1324             elementData[i] = operator.apply((E) elementData[i]);
1325         }
1326         if (modCount != expectedModCount) {
1327             throw new ConcurrentModificationException();
1328         }
1329         modCount++;
1330     }
1331 
1332     @SuppressWarnings("unchecked")
1333     @Override
1334     public synchronized void sort(Comparator<? super E> c) {
1335         final int expectedModCount = modCount;
1336         Arrays.sort((E[]) elementData, 0, elementCount, c);
1337         if (modCount != expectedModCount) {
1338             throw new ConcurrentModificationException();
1339         }
1340         modCount++;
1341     }
1342 
1343     /**
1344      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1345      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1346      * list.
1347      *
1348      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1349      * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1350      * Overriding implementations should document the reporting of additional
1351      * characteristic values.
1352      *
1353      * @return a {@code Spliterator} over the elements in this list
1354      * @since 1.8
1355      */
1356     @Override
1357     public Spliterator<E> spliterator() {
1358         return new VectorSpliterator<>(this, null, 0, -1, 0);
1359     }
1360 
1361     /** Similar to ArrayList Spliterator */
1362     static final class VectorSpliterator<E> implements Spliterator<E> {
1363         private final Vector<E> list;
1364         private Object[] array;
1365         private int index; // current index, modified on advance/split
1366         private int fence; // -1 until used; then one past last index
1367         private int expectedModCount; // initialized when fence set
1368 
1369         /** Create new spliterator covering the given  range */
1370         VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1371                           int expectedModCount) {
1372             this.list = list;
1373             this.array = array;
1374             this.index = origin;
1375             this.fence = fence;
1376             this.expectedModCount = expectedModCount;
1377         }
1378 
1379         private int getFence() { // initialize on first use
1380             int hi;
1381             if ((hi = fence) < 0) {
1382                 synchronized(list) {
1383                     array = list.elementData;
1384                     expectedModCount = list.modCount;
1385                     hi = fence = list.elementCount;
1386                 }
1387             }
1388             return hi;
1389         }
1390 
1391         public Spliterator<E> trySplit() {
1392             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1393             return (lo >= mid) ? null :
1394                 new VectorSpliterator<>(list, array, lo, index = mid,
1395                                         expectedModCount);
1396         }
1397 
1398         @SuppressWarnings("unchecked")
1399         public boolean tryAdvance(Consumer<? super E> action) {
1400             int i;
1401             if (action == null)
1402                 throw new NullPointerException();
1403             if (getFence() > (i = index)) {
1404                 index = i + 1;
1405                 action.accept((E)array[i]);
1406                 if (list.modCount != expectedModCount)
1407                     throw new ConcurrentModificationException();
1408                 return true;
1409             }
1410             return false;
1411         }
1412 
1413         @SuppressWarnings("unchecked")
1414         public void forEachRemaining(Consumer<? super E> action) {
1415             int i, hi; // hoist accesses and checks from loop
1416             Vector<E> lst; Object[] a;
1417             if (action == null)
1418                 throw new NullPointerException();
1419             if ((lst = list) != null) {
1420                 if ((hi = fence) < 0) {
1421                     synchronized(lst) {
1422                         expectedModCount = lst.modCount;
1423                         a = array = lst.elementData;
1424                         hi = fence = lst.elementCount;
1425                     }
1426                 }
1427                 else
1428                     a = array;
1429                 if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1430                     while (i < hi)
1431                         action.accept((E) a[i++]);
1432                     if (lst.modCount == expectedModCount)
1433                         return;
1434                 }
1435             }
1436             throw new ConcurrentModificationException();
1437         }
1438 
1439         public long estimateSize() {
1440             return getFence() - index;
1441         }
1442 
1443         public int characteristics() {
1444             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1445         }
1446     }
1447 }