ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/Vector.java
(Generate patch)

Comparing jsr166/src/main/java/util/Vector.java (file contents):
Revision 1.25 by jsr166, Mon May 19 00:28:21 2008 UTC vs.
Revision 1.56 by jsr166, Fri Aug 30 18:05:39 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright 1994-2007 Sun Microsystems, Inc.  All Rights Reserved.
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.  Sun designates this
7 > * published by the Free Software Foundation.  Oracle designates this
8   * particular file as subject to the "Classpath" exception as provided
9 < * by Sun in the LICENSE file that accompanied this code.
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
# Line 18 | Line 18
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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 < * CA 95054 USA or visit www.sun.com if you need additional information or
23 < * have any questions.
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
# Line 41 | Line 50 | package java.util;
50   * capacity of a vector before inserting a large number of
51   * components; this reduces the amount of incremental reallocation.
52   *
53 < * <p><a name="fail-fast"/>
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
# Line 52 | Line 61 | package java.util;
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.
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
# Line 64 | Line 75 | package java.util;
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}/../technotes/guides/collections/index.html">
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   JDK1.0
90 > * @since   1.0
91   */
92   public class Vector<E>
93      extends AbstractList<E>
# Line 111 | Line 124 | public class Vector<E>
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      /**
# Line 166 | Line 180 | public class Vector<E>
180      public Vector(Collection<? extends E> c) {
181          elementData = c.toArray();
182          elementCount = elementData.length;
183 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
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      }
# Line 222 | Line 237 | public class Vector<E>
237       * @param minCapacity the desired minimum capacity
238       */
239      public synchronized void ensureCapacity(int minCapacity) {
240 <        modCount++;
241 <        ensureCapacityHelper(minCapacity);
240 >        if (minCapacity > 0) {
241 >            modCount++;
242 >            if (minCapacity > elementData.length)
243 >                grow(minCapacity);
244 >        }
245      }
246  
247      /**
248 <     * This implements the unsynchronized semantics of ensureCapacity.
249 <     * Synchronized methods in this class can internally call this
232 <     * method for ensuring capacity without incurring the cost of an
233 <     * extra synchronization.
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 <     * @see #ensureCapacity(int)
251 >     * @param minCapacity the desired minimum capacity
252 >     * @throws OutOfMemoryError if minCapacity is less than zero
253       */
254 <    private void ensureCapacityHelper(int minCapacity) {
254 >    private Object[] grow(int minCapacity) {
255          int oldCapacity = elementData.length;
256 <        if (minCapacity > oldCapacity) {
257 <            Object[] oldData = elementData;
258 <            int newCapacity = (capacityIncrement > 0) ?
259 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
260 <            if (newCapacity < minCapacity) {
261 <                newCapacity = minCapacity;
262 <            }
263 <            elementData = Arrays.copyOf(elementData, newCapacity);
264 <        }
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      /**
# Line 258 | Line 275 | public class Vector<E>
275       */
276      public synchronized void setSize(int newSize) {
277          modCount++;
278 <        if (newSize > elementCount) {
279 <            ensureCapacityHelper(newSize);
280 <        } else {
281 <            for (int i = newSize ; i < elementCount ; i++) {
282 <                elementData[i] = null;
266 <            }
267 <        }
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  
# Line 303 | Line 318 | public class Vector<E>
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.
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
# Line 331 | Line 348 | public class Vector<E>
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 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
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
# Line 344 | Line 361 | public class Vector<E>
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 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
364 >     * {@code Objects.equals(o, get(i))},
365       * or -1 if there is no such index.
366       *
367       * @param o element to search for
# Line 360 | Line 377 | public class Vector<E>
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 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
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
# Line 388 | Line 405 | public class Vector<E>
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 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
408 >     * {@code Objects.equals(o, get(i))},
409       * or -1 if there is no such index.
410       *
411       * @param o element to search for
# Line 404 | Line 421 | public class Vector<E>
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 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
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
# Line 468 | Line 485 | public class Vector<E>
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()&nbsp;-&nbsp;1</code>.
488 >     *          {@code size() - 1}
489       * @throws NoSuchElementException if this vector is empty
490       */
491      public synchronized E lastElement() {
# Line 526 | Line 543 | public class Vector<E>
543       *         ({@code index < 0 || index >= size()})
544       */
545      public synchronized void removeElementAt(int index) {
529        modCount++;
546          if (index >= elementCount) {
547              throw new ArrayIndexOutOfBoundsException(index + " >= " +
548                                                       elementCount);
# Line 538 | Line 554 | public class Vector<E>
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      /**
# Line 566 | Line 584 | public class Vector<E>
584       *         ({@code index < 0 || index > size()})
585       */
586      public synchronized void insertElementAt(E obj, int index) {
569        modCount++;
587          if (index > elementCount) {
588              throw new ArrayIndexOutOfBoundsException(index
589                                                       + " > " + elementCount);
590          }
591 <        ensureCapacityHelper(elementCount + 1);
592 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
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++;
600 >        elementCount = s + 1;
601      }
602  
603      /**
# Line 590 | Line 613 | public class Vector<E>
613       */
614      public synchronized void addElement(E obj) {
615          modCount++;
616 <        ensureCapacityHelper(elementCount + 1);
594 <        elementData[elementCount++] = obj;
616 >        add(obj, elementData, elementCount);
617      }
618  
619      /**
# Line 626 | Line 648 | public class Vector<E>
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++;
630        // Let gc do its work
631        for (int i = 0; i < elementCount; i++)
632            elementData[i] = null;
633
634        elementCount = 0;
655      }
656  
657      /**
# Line 644 | Line 664 | public class Vector<E>
664      public synchronized Object clone() {
665          try {
666              @SuppressWarnings("unchecked")
667 <                Vector<E> v = (Vector<E>) super.clone();
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();
673 >            throw new InternalError(e);
674          }
675      }
676  
# Line 678 | Line 698 | public class Vector<E>
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 is not a supertype
708 <     * of the runtime type of every element in this 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       */
# Line 707 | Line 730 | public class Vector<E>
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       *
# Line 744 | Line 772 | public class Vector<E>
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
# Line 752 | Line 793 | public class Vector<E>
793       */
794      public synchronized boolean add(E e) {
795          modCount++;
796 <        ensureCapacityHelper(elementCount + 1);
756 <        elementData[elementCount++] = e;
796 >        add(e, elementData, elementCount);
797          return true;
798      }
799  
# Line 761 | Line 801 | public class Vector<E>
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 (o==null ? get(i)==null : o.equals(get(i)))} (if such
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
# Line 792 | Line 832 | public class Vector<E>
832       * Shifts any subsequent elements to the left (subtracts one from their
833       * indices).  Returns the element that was removed from the Vector.
834       *
795     * @throws ArrayIndexOutOfBoundsException if the index is out of range
796     *         ({@code index < 0 || index >= size()})
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) {
# Line 810 | Line 850 | public class Vector<E>
850                               numMoved);
851          elementData[--elementCount] = null; // Let gc do its work
852  
853 +        // checkInvariants();
854          return oldValue;
855      }
856  
# Line 852 | Line 893 | public class Vector<E>
893       * @throws NullPointerException if the specified collection is null
894       * @since 1.2
895       */
896 <    public synchronized boolean addAll(Collection<? extends E> c) {
856 <        modCount++;
896 >    public boolean addAll(Collection<? extends E> c) {
897          Object[] a = c.toArray();
898 +        modCount++;
899          int numNew = a.length;
900 <        ensureCapacityHelper(elementCount + numNew);
901 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
902 <        elementCount += numNew;
903 <        return numNew != 0;
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      /**
# Line 870 | Line 919 | public class Vector<E>
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 (optional)
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 (optional), or if the specified collection is 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 synchronized boolean removeAll(Collection<?> c) {
932 <        return super.removeAll(c);
931 >    public boolean removeAll(Collection<?> c) {
932 >        Objects.requireNonNull(c);
933 >        return bulkRemove(e -> c.contains(e));
934      }
935  
936      /**
# Line 890 | Line 943 | public class Vector<E>
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 (optional)
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 (optional), or if the specified collection is 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 synchronized boolean retainAll(Collection<?> c)  {
956 <        return super.retainAll(c);
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      /**
# Line 918 | Line 1033 | public class Vector<E>
1033       * @since 1.2
1034       */
1035      public synchronized boolean addAll(int index, Collection<? extends E> c) {
921        modCount++;
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 <        ensureCapacityHelper(elementCount + numNew);
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 = elementCount - index;
1049 >        int numMoved = s - index;
1050          if (numMoved > 0)
1051 <            System.arraycopy(elementData, index, elementData, index + numNew,
1051 >            System.arraycopy(elementData, index,
1052 >                             elementData, index + numNew,
1053                               numMoved);
933
1054          System.arraycopy(a, 0, elementData, index, numNew);
1055 <        elementCount += numNew;
1056 <        return numNew != 0;
1055 >        elementCount = s + numNew;
1056 >        // checkInvariants();
1057 >        return true;
1058      }
1059  
1060      /**
# Line 941 | Line 1062 | public class Vector<E>
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 (e1==null ? e2==null :
1066 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
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
# Line 1015 | Line 1136 | public class Vector<E>
1136       */
1137      protected synchronized void removeRange(int fromIndex, int toIndex) {
1138          modCount++;
1139 <        int numMoved = elementCount - toIndex;
1140 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1141 <                         numMoved);
1139 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1140 >        // checkInvariants();
1141 >    }
1142  
1143 <        // Let gc do its work
1144 <        int newElementCount = elementCount - (toIndex-fromIndex);
1145 <        while (elementCount != newElementCount)
1146 <            elementData[--elementCount] = null;
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 <     * Save the state of the {@code Vector} instance to a stream (that
1152 <     * is, serialize it).  This method is present merely for synchronization.
1153 <     * It just calls the default writeObject method.
1154 <     */
1155 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1156 <        throws java.io.IOException
1157 <    {
1158 <        s.defaultWriteObject();
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      /**
# Line 1114 | Line 1272 | public class Vector<E>
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();
# Line 1172 | Line 1351 | public class Vector<E>
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   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines