ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
Revision: 1.56
Committed: Fri Aug 30 18:05:39 2019 UTC (4 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.55: +3 -0 lines
Log Message:
accommodate 8229997: Apply java.io.Serial annotations in java.base

File Contents

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