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