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.26 by jsr166, Wed Jul 22 00:00:07 2009 UTC vs.
Revision 1.58 by jsr166, Fri Jul 24 20:57:26 2020 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright 1994-2008 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 89 | Line 102 | public class Vector<E>
102       *
103       * @serial
104       */
105 +    @SuppressWarnings("serial") // Conditionally serializable
106      protected Object[] elementData;
107  
108      /**
# Line 111 | Line 125 | public class Vector<E>
125      protected int capacityIncrement;
126  
127      /** use serialVersionUID from JDK 1.0.2 for interoperability */
128 +    // OPENJDK @java.io.Serial
129      private static final long serialVersionUID = -2767605614048989439L;
130  
131      /**
# Line 164 | Line 179 | public class Vector<E>
179       * @since   1.2
180       */
181      public Vector(Collection<? extends E> c) {
182 <        elementData = c.toArray();
183 <        elementCount = elementData.length;
184 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
185 <        if (elementData.getClass() != Object[].class)
186 <            elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
182 >        Object[] a = c.toArray();
183 >        elementCount = a.length;
184 >        if (c.getClass() == ArrayList.class) {
185 >            elementData = a;
186 >        } else {
187 >            elementData = Arrays.copyOf(a, elementCount, Object[].class);
188 >        }
189      }
190  
191      /**
# Line 222 | Line 239 | public class Vector<E>
239       * @param minCapacity the desired minimum capacity
240       */
241      public synchronized void ensureCapacity(int minCapacity) {
242 <        modCount++;
243 <        ensureCapacityHelper(minCapacity);
242 >        if (minCapacity > 0) {
243 >            modCount++;
244 >            if (minCapacity > elementData.length)
245 >                grow(minCapacity);
246 >        }
247      }
248  
249      /**
250 <     * This implements the unsynchronized semantics of ensureCapacity.
251 <     * Synchronized methods in this class can internally call this
232 <     * method for ensuring capacity without incurring the cost of an
233 <     * extra synchronization.
250 >     * Increases the capacity to ensure that it can hold at least the
251 >     * number of elements specified by the minimum capacity argument.
252       *
253 <     * @see #ensureCapacity(int)
253 >     * @param minCapacity the desired minimum capacity
254 >     * @throws OutOfMemoryError if minCapacity is less than zero
255       */
256 <    private void ensureCapacityHelper(int minCapacity) {
256 >    private Object[] grow(int minCapacity) {
257          int oldCapacity = elementData.length;
258 <        if (minCapacity > oldCapacity) {
259 <            Object[] oldData = elementData;
260 <            int newCapacity = (capacityIncrement > 0) ?
261 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
262 <            if (newCapacity < minCapacity) {
263 <                newCapacity = minCapacity;
264 <            }
265 <            elementData = Arrays.copyOf(elementData, newCapacity);
266 <        }
258 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
259 >                minCapacity - oldCapacity, /* minimum growth */
260 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
261 >                                           /* preferred growth */);
262 >        return elementData = Arrays.copyOf(elementData, newCapacity);
263 >    }
264 >
265 >    private Object[] grow() {
266 >        return grow(elementCount + 1);
267      }
268  
269      /**
# Line 258 | Line 277 | public class Vector<E>
277       */
278      public synchronized void setSize(int newSize) {
279          modCount++;
280 <        if (newSize > elementCount) {
281 <            ensureCapacityHelper(newSize);
282 <        } else {
283 <            for (int i = newSize ; i < elementCount ; i++) {
284 <                elementData[i] = null;
266 <            }
267 <        }
280 >        if (newSize > elementData.length)
281 >            grow(newSize);
282 >        final Object[] es = elementData;
283 >        for (int to = elementCount, i = newSize; i < to; i++)
284 >            es[i] = null;
285          elementCount = newSize;
286      }
287  
# Line 303 | Line 320 | public class Vector<E>
320       * Returns an enumeration of the components of this vector. The
321       * returned {@code Enumeration} object will generate all items in
322       * this vector. The first item generated is the item at index {@code 0},
323 <     * then the item at index {@code 1}, and so on.
323 >     * then the item at index {@code 1}, and so on. If the vector is
324 >     * structurally modified while enumerating over the elements then the
325 >     * results of enumerating are undefined.
326       *
327       * @return  an enumeration of the components of this vector
328       * @see     Iterator
# Line 331 | Line 350 | public class Vector<E>
350       * Returns {@code true} if this vector contains the specified element.
351       * More formally, returns {@code true} if and only if this vector
352       * contains at least one element {@code e} such that
353 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
353 >     * {@code Objects.equals(o, e)}.
354       *
355       * @param o element whose presence in this vector is to be tested
356       * @return {@code true} if this vector contains the specified element
# Line 344 | Line 363 | public class Vector<E>
363       * Returns the index of the first occurrence of the specified element
364       * in this vector, or -1 if this vector does not contain the element.
365       * More formally, returns the lowest index {@code i} such that
366 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
366 >     * {@code Objects.equals(o, get(i))},
367       * or -1 if there is no such index.
368       *
369       * @param o element to search for
# Line 360 | Line 379 | public class Vector<E>
379       * this vector, searching forwards from {@code index}, or returns -1 if
380       * the element is not found.
381       * More formally, returns the lowest index {@code i} such that
382 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
382 >     * {@code (i >= index && Objects.equals(o, get(i)))},
383       * or -1 if there is no such index.
384       *
385       * @param o element to search for
# Line 388 | Line 407 | public class Vector<E>
407       * Returns the index of the last occurrence of the specified element
408       * in this vector, or -1 if this vector does not contain the element.
409       * More formally, returns the highest index {@code i} such that
410 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
410 >     * {@code Objects.equals(o, get(i))},
411       * or -1 if there is no such index.
412       *
413       * @param o element to search for
# Line 404 | Line 423 | public class Vector<E>
423       * this vector, searching backwards from {@code index}, or returns -1 if
424       * the element is not found.
425       * More formally, returns the highest index {@code i} such that
426 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
426 >     * {@code (i <= index && Objects.equals(o, get(i)))},
427       * or -1 if there is no such index.
428       *
429       * @param o element to search for
# Line 468 | Line 487 | public class Vector<E>
487       * Returns the last component of the vector.
488       *
489       * @return  the last component of the vector, i.e., the component at index
490 <     *          <code>size()&nbsp;-&nbsp;1</code>.
490 >     *          {@code size() - 1}
491       * @throws NoSuchElementException if this vector is empty
492       */
493      public synchronized E lastElement() {
# Line 526 | Line 545 | public class Vector<E>
545       *         ({@code index < 0 || index >= size()})
546       */
547      public synchronized void removeElementAt(int index) {
529        modCount++;
548          if (index >= elementCount) {
549              throw new ArrayIndexOutOfBoundsException(index + " >= " +
550                                                       elementCount);
# Line 538 | Line 556 | public class Vector<E>
556          if (j > 0) {
557              System.arraycopy(elementData, index + 1, elementData, index, j);
558          }
559 +        modCount++;
560          elementCount--;
561          elementData[elementCount] = null; /* to let gc do its work */
562 +        // checkInvariants();
563      }
564  
565      /**
# Line 566 | Line 586 | public class Vector<E>
586       *         ({@code index < 0 || index > size()})
587       */
588      public synchronized void insertElementAt(E obj, int index) {
569        modCount++;
589          if (index > elementCount) {
590              throw new ArrayIndexOutOfBoundsException(index
591                                                       + " > " + elementCount);
592          }
593 <        ensureCapacityHelper(elementCount + 1);
594 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
593 >        modCount++;
594 >        final int s = elementCount;
595 >        Object[] elementData = this.elementData;
596 >        if (s == elementData.length)
597 >            elementData = grow();
598 >        System.arraycopy(elementData, index,
599 >                         elementData, index + 1,
600 >                         s - index);
601          elementData[index] = obj;
602 <        elementCount++;
602 >        elementCount = s + 1;
603      }
604  
605      /**
# Line 590 | Line 615 | public class Vector<E>
615       */
616      public synchronized void addElement(E obj) {
617          modCount++;
618 <        ensureCapacityHelper(elementCount + 1);
594 <        elementData[elementCount++] = obj;
618 >        add(obj, elementData, elementCount);
619      }
620  
621      /**
# Line 626 | Line 650 | public class Vector<E>
650       * method (which is part of the {@link List} interface).
651       */
652      public synchronized void removeAllElements() {
653 +        final Object[] es = elementData;
654 +        for (int to = elementCount, i = elementCount = 0; i < to; i++)
655 +            es[i] = null;
656          modCount++;
630        // Let gc do its work
631        for (int i = 0; i < elementCount; i++)
632            elementData[i] = null;
633
634        elementCount = 0;
657      }
658  
659      /**
# Line 644 | Line 666 | public class Vector<E>
666      public synchronized Object clone() {
667          try {
668              @SuppressWarnings("unchecked")
669 <                Vector<E> v = (Vector<E>) super.clone();
669 >            Vector<E> v = (Vector<E>) super.clone();
670              v.elementData = Arrays.copyOf(elementData, elementCount);
671              v.modCount = 0;
672              return v;
673          } catch (CloneNotSupportedException e) {
674              // this shouldn't happen, since we are Cloneable
675 <            throw new InternalError();
675 >            throw new InternalError(e);
676          }
677      }
678  
# Line 678 | Line 700 | public class Vector<E>
700       * of the Vector <em>only</em> if the caller knows that the Vector
701       * does not contain any null elements.)
702       *
703 +     * @param <T> type of array elements. The same type as {@code <E>} or a
704 +     * supertype of {@code <E>}.
705       * @param a the array into which the elements of the Vector are to
706       *          be stored, if it is big enough; otherwise, a new array of the
707       *          same runtime type is allocated for this purpose.
708       * @return an array containing the elements of the Vector
709 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
710 <     * of the runtime type of every element in this Vector
709 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
710 >     * a supertype of the runtime type, {@code <E>}, of every element in this
711 >     * Vector
712       * @throws NullPointerException if the given array is null
713       * @since 1.2
714       */
# Line 707 | Line 732 | public class Vector<E>
732          return (E) elementData[index];
733      }
734  
735 +    @SuppressWarnings("unchecked")
736 +    static <E> E elementAt(Object[] es, int index) {
737 +        return (E) es[index];
738 +    }
739 +
740      /**
741       * Returns the element at the specified position in this Vector.
742       *
# Line 744 | Line 774 | public class Vector<E>
774      }
775  
776      /**
777 +     * This helper method split out from add(E) to keep method
778 +     * bytecode size under 35 (the -XX:MaxInlineSize default value),
779 +     * which helps when add(E) is called in a C1-compiled loop.
780 +     */
781 +    private void add(E e, Object[] elementData, int s) {
782 +        if (s == elementData.length)
783 +            elementData = grow();
784 +        elementData[s] = e;
785 +        elementCount = s + 1;
786 +        // checkInvariants();
787 +    }
788 +
789 +    /**
790       * Appends the specified element to the end of this Vector.
791       *
792       * @param e element to be appended to this Vector
# Line 752 | Line 795 | public class Vector<E>
795       */
796      public synchronized boolean add(E e) {
797          modCount++;
798 <        ensureCapacityHelper(elementCount + 1);
756 <        elementData[elementCount++] = e;
798 >        add(e, elementData, elementCount);
799          return true;
800      }
801  
# Line 761 | Line 803 | public class Vector<E>
803       * Removes the first occurrence of the specified element in this Vector
804       * If the Vector does not contain the element, it is unchanged.  More
805       * formally, removes the element with the lowest index i such that
806 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
806 >     * {@code Objects.equals(o, get(i))} (if such
807       * an element exists).
808       *
809       * @param o element to be removed from this Vector, if present
# Line 792 | Line 834 | public class Vector<E>
834       * Shifts any subsequent elements to the left (subtracts one from their
835       * indices).  Returns the element that was removed from the Vector.
836       *
795     * @throws ArrayIndexOutOfBoundsException if the index is out of range
796     *         ({@code index < 0 || index >= size()})
837       * @param index the index of the element to be removed
838       * @return element that was removed
839 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
840 +     *         ({@code index < 0 || index >= size()})
841       * @since 1.2
842       */
843      public synchronized E remove(int index) {
# Line 810 | Line 852 | public class Vector<E>
852                               numMoved);
853          elementData[--elementCount] = null; // Let gc do its work
854  
855 +        // checkInvariants();
856          return oldValue;
857      }
858  
# Line 852 | Line 895 | public class Vector<E>
895       * @throws NullPointerException if the specified collection is null
896       * @since 1.2
897       */
898 <    public synchronized boolean addAll(Collection<? extends E> c) {
856 <        modCount++;
898 >    public boolean addAll(Collection<? extends E> c) {
899          Object[] a = c.toArray();
900 +        modCount++;
901          int numNew = a.length;
902 <        ensureCapacityHelper(elementCount + numNew);
903 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
904 <        elementCount += numNew;
905 <        return numNew != 0;
902 >        if (numNew == 0)
903 >            return false;
904 >        synchronized (this) {
905 >            Object[] elementData = this.elementData;
906 >            final int s = elementCount;
907 >            if (numNew > elementData.length - s)
908 >                elementData = grow(s + numNew);
909 >            System.arraycopy(a, 0, elementData, s, numNew);
910 >            elementCount = s + numNew;
911 >            // checkInvariants();
912 >            return true;
913 >        }
914      }
915  
916      /**
# Line 870 | Line 921 | public class Vector<E>
921       * @return true if this Vector changed as a result of the call
922       * @throws ClassCastException if the types of one or more elements
923       *         in this vector are incompatible with the specified
924 <     *         collection (optional)
924 >     *         collection
925 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
926       * @throws NullPointerException if this vector contains one or more null
927       *         elements and the specified collection does not support null
928 <     *         elements (optional), or if the specified collection is null
928 >     *         elements
929 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
930 >     *         or if the specified collection is null
931       * @since 1.2
932       */
933 <    public synchronized boolean removeAll(Collection<?> c) {
934 <        return super.removeAll(c);
933 >    public boolean removeAll(Collection<?> c) {
934 >        Objects.requireNonNull(c);
935 >        return bulkRemove(e -> c.contains(e));
936      }
937  
938      /**
# Line 890 | Line 945 | public class Vector<E>
945       * @return true if this Vector changed as a result of the call
946       * @throws ClassCastException if the types of one or more elements
947       *         in this vector are incompatible with the specified
948 <     *         collection (optional)
948 >     *         collection
949 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
950       * @throws NullPointerException if this vector contains one or more null
951       *         elements and the specified collection does not support null
952 <     *         elements (optional), or if the specified collection is null
952 >     *         elements
953 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
954 >     *         or if the specified collection is null
955       * @since 1.2
956       */
957 <    public synchronized boolean retainAll(Collection<?> c)  {
958 <        return super.retainAll(c);
957 >    public boolean retainAll(Collection<?> c) {
958 >        Objects.requireNonNull(c);
959 >        return bulkRemove(e -> !c.contains(e));
960 >    }
961 >
962 >    /**
963 >     * @throws NullPointerException {@inheritDoc}
964 >     */
965 >    @Override
966 >    public boolean removeIf(Predicate<? super E> filter) {
967 >        Objects.requireNonNull(filter);
968 >        return bulkRemove(filter);
969 >    }
970 >
971 >    // A tiny bit set implementation
972 >
973 >    private static long[] nBits(int n) {
974 >        return new long[((n - 1) >> 6) + 1];
975 >    }
976 >    private static void setBit(long[] bits, int i) {
977 >        bits[i >> 6] |= 1L << i;
978 >    }
979 >    private static boolean isClear(long[] bits, int i) {
980 >        return (bits[i >> 6] & (1L << i)) == 0;
981 >    }
982 >
983 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
984 >        int expectedModCount = modCount;
985 >        final Object[] es = elementData;
986 >        final int end = elementCount;
987 >        int i;
988 >        // Optimize for initial run of survivors
989 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
990 >            ;
991 >        // Tolerate predicates that reentrantly access the collection for
992 >        // read (but writers still get CME), so traverse once to find
993 >        // elements to delete, a second pass to physically expunge.
994 >        if (i < end) {
995 >            final int beg = i;
996 >            final long[] deathRow = nBits(end - beg);
997 >            deathRow[0] = 1L;   // set bit 0
998 >            for (i = beg + 1; i < end; i++)
999 >                if (filter.test(elementAt(es, i)))
1000 >                    setBit(deathRow, i - beg);
1001 >            if (modCount != expectedModCount)
1002 >                throw new ConcurrentModificationException();
1003 >            modCount++;
1004 >            int w = beg;
1005 >            for (i = beg; i < end; i++)
1006 >                if (isClear(deathRow, i - beg))
1007 >                    es[w++] = es[i];
1008 >            for (i = elementCount = w; i < end; i++)
1009 >                es[i] = null;
1010 >            // checkInvariants();
1011 >            return true;
1012 >        } else {
1013 >            if (modCount != expectedModCount)
1014 >                throw new ConcurrentModificationException();
1015 >            // checkInvariants();
1016 >            return false;
1017 >        }
1018      }
1019  
1020      /**
# Line 918 | Line 1035 | public class Vector<E>
1035       * @since 1.2
1036       */
1037      public synchronized boolean addAll(int index, Collection<? extends E> c) {
921        modCount++;
1038          if (index < 0 || index > elementCount)
1039              throw new ArrayIndexOutOfBoundsException(index);
1040  
1041          Object[] a = c.toArray();
1042 +        modCount++;
1043          int numNew = a.length;
1044 <        ensureCapacityHelper(elementCount + numNew);
1044 >        if (numNew == 0)
1045 >            return false;
1046 >        Object[] elementData = this.elementData;
1047 >        final int s = elementCount;
1048 >        if (numNew > elementData.length - s)
1049 >            elementData = grow(s + numNew);
1050  
1051 <        int numMoved = elementCount - index;
1051 >        int numMoved = s - index;
1052          if (numMoved > 0)
1053 <            System.arraycopy(elementData, index, elementData, index + numNew,
1053 >            System.arraycopy(elementData, index,
1054 >                             elementData, index + numNew,
1055                               numMoved);
933
1056          System.arraycopy(a, 0, elementData, index, numNew);
1057 <        elementCount += numNew;
1058 <        return numNew != 0;
1057 >        elementCount = s + numNew;
1058 >        // checkInvariants();
1059 >        return true;
1060      }
1061  
1062      /**
# Line 941 | Line 1064 | public class Vector<E>
1064       * true if and only if the specified Object is also a List, both Lists
1065       * have the same size, and all corresponding pairs of elements in the two
1066       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1067 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1068 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1067 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1068 >     * In other words, two Lists are defined to be
1069       * equal if they contain the same elements in the same order.
1070       *
1071       * @param o the Object to be compared for equality with this Vector
# Line 1015 | Line 1138 | public class Vector<E>
1138       */
1139      protected synchronized void removeRange(int fromIndex, int toIndex) {
1140          modCount++;
1141 <        int numMoved = elementCount - toIndex;
1142 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1143 <                         numMoved);
1141 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1142 >        // checkInvariants();
1143 >    }
1144  
1145 <        // Let gc do its work
1146 <        int newElementCount = elementCount - (toIndex-fromIndex);
1147 <        while (elementCount != newElementCount)
1148 <            elementData[--elementCount] = null;
1145 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1146 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1147 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1148 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1149 >            es[i] = null;
1150      }
1151  
1152      /**
1153 <     * Save the state of the {@code Vector} instance to a stream (that
1154 <     * is, serialize it).  This method is present merely for synchronization.
1155 <     * It just calls the default writeObject method.
1156 <     */
1157 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1158 <        throws java.io.IOException
1159 <    {
1160 <        s.defaultWriteObject();
1153 >     * Loads a {@code Vector} instance from a stream
1154 >     * (that is, deserializes it).
1155 >     * This method performs checks to ensure the consistency
1156 >     * of the fields.
1157 >     *
1158 >     * @param in the stream
1159 >     * @throws java.io.IOException if an I/O error occurs
1160 >     * @throws ClassNotFoundException if the stream contains data
1161 >     *         of a non-existing class
1162 >     */
1163 >    // OPENJDK @java.io.Serial
1164 >    private void readObject(ObjectInputStream in)
1165 >            throws IOException, ClassNotFoundException {
1166 >        ObjectInputStream.GetField gfields = in.readFields();
1167 >        int count = gfields.get("elementCount", 0);
1168 >        Object[] data = (Object[])gfields.get("elementData", null);
1169 >        if (count < 0 || data == null || count > data.length) {
1170 >            throw new StreamCorruptedException("Inconsistent vector internals");
1171 >        }
1172 >        elementCount = count;
1173 >        elementData = data.clone();
1174 >    }
1175 >
1176 >    /**
1177 >     * Saves the state of the {@code Vector} instance to a stream
1178 >     * (that is, serializes it).
1179 >     * This method performs synchronization to ensure the consistency
1180 >     * of the serialized data.
1181 >     *
1182 >     * @param s the stream
1183 >     * @throws java.io.IOException if an I/O error occurs
1184 >     */
1185 >    // OPENJDK @java.io.Serial
1186 >    private void writeObject(java.io.ObjectOutputStream s)
1187 >            throws java.io.IOException {
1188 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1189 >        final Object[] data;
1190 >        synchronized (this) {
1191 >            fields.put("capacityIncrement", capacityIncrement);
1192 >            fields.put("elementCount", elementCount);
1193 >            data = elementData.clone();
1194 >        }
1195 >        fields.put("elementData", data);
1196 >        s.writeFields();
1197      }
1198  
1199      /**
# Line 1114 | Line 1274 | public class Vector<E>
1274              lastRet = -1;
1275          }
1276  
1277 +        @Override
1278 +        public void forEachRemaining(Consumer<? super E> action) {
1279 +            Objects.requireNonNull(action);
1280 +            synchronized (Vector.this) {
1281 +                final int size = elementCount;
1282 +                int i = cursor;
1283 +                if (i >= size) {
1284 +                    return;
1285 +                }
1286 +                final Object[] es = elementData;
1287 +                if (i >= es.length)
1288 +                    throw new ConcurrentModificationException();
1289 +                while (i < size && modCount == expectedModCount)
1290 +                    action.accept(elementAt(es, i++));
1291 +                // update once at end of iteration to reduce heap write traffic
1292 +                cursor = i;
1293 +                lastRet = i - 1;
1294 +                checkForComodification();
1295 +            }
1296 +        }
1297 +
1298          final void checkForComodification() {
1299              if (modCount != expectedModCount)
1300                  throw new ConcurrentModificationException();
# Line 1172 | Line 1353 | public class Vector<E>
1353              lastRet = -1;
1354          }
1355      }
1356 +
1357 +    /**
1358 +     * @throws NullPointerException {@inheritDoc}
1359 +     */
1360 +    @Override
1361 +    public synchronized void forEach(Consumer<? super E> action) {
1362 +        Objects.requireNonNull(action);
1363 +        final int expectedModCount = modCount;
1364 +        final Object[] es = elementData;
1365 +        final int size = elementCount;
1366 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1367 +            action.accept(elementAt(es, i));
1368 +        if (modCount != expectedModCount)
1369 +            throw new ConcurrentModificationException();
1370 +        // checkInvariants();
1371 +    }
1372 +
1373 +    /**
1374 +     * @throws NullPointerException {@inheritDoc}
1375 +     */
1376 +    @Override
1377 +    public synchronized void replaceAll(UnaryOperator<E> operator) {
1378 +        Objects.requireNonNull(operator);
1379 +        final int expectedModCount = modCount;
1380 +        final Object[] es = elementData;
1381 +        final int size = elementCount;
1382 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1383 +            es[i] = operator.apply(elementAt(es, i));
1384 +        if (modCount != expectedModCount)
1385 +            throw new ConcurrentModificationException();
1386 +        // TODO(8203662): remove increment of modCount from ...
1387 +        modCount++;
1388 +        // checkInvariants();
1389 +    }
1390 +
1391 +    @SuppressWarnings("unchecked")
1392 +    @Override
1393 +    public synchronized void sort(Comparator<? super E> c) {
1394 +        final int expectedModCount = modCount;
1395 +        Arrays.sort((E[]) elementData, 0, elementCount, c);
1396 +        if (modCount != expectedModCount)
1397 +            throw new ConcurrentModificationException();
1398 +        modCount++;
1399 +        // checkInvariants();
1400 +    }
1401 +
1402 +    /**
1403 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1404 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1405 +     * list.
1406 +     *
1407 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1408 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1409 +     * Overriding implementations should document the reporting of additional
1410 +     * characteristic values.
1411 +     *
1412 +     * @return a {@code Spliterator} over the elements in this list
1413 +     * @since 1.8
1414 +     */
1415 +    @Override
1416 +    public Spliterator<E> spliterator() {
1417 +        return new VectorSpliterator(null, 0, -1, 0);
1418 +    }
1419 +
1420 +    /** Similar to ArrayList Spliterator */
1421 +    final class VectorSpliterator implements Spliterator<E> {
1422 +        private Object[] array;
1423 +        private int index; // current index, modified on advance/split
1424 +        private int fence; // -1 until used; then one past last index
1425 +        private int expectedModCount; // initialized when fence set
1426 +
1427 +        /** Creates new spliterator covering the given range. */
1428 +        VectorSpliterator(Object[] array, int origin, int fence,
1429 +                          int expectedModCount) {
1430 +            this.array = array;
1431 +            this.index = origin;
1432 +            this.fence = fence;
1433 +            this.expectedModCount = expectedModCount;
1434 +        }
1435 +
1436 +        private int getFence() { // initialize on first use
1437 +            int hi;
1438 +            if ((hi = fence) < 0) {
1439 +                synchronized (Vector.this) {
1440 +                    array = elementData;
1441 +                    expectedModCount = modCount;
1442 +                    hi = fence = elementCount;
1443 +                }
1444 +            }
1445 +            return hi;
1446 +        }
1447 +
1448 +        public Spliterator<E> trySplit() {
1449 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1450 +            return (lo >= mid) ? null :
1451 +                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1452 +        }
1453 +
1454 +        @SuppressWarnings("unchecked")
1455 +        public boolean tryAdvance(Consumer<? super E> action) {
1456 +            Objects.requireNonNull(action);
1457 +            int i;
1458 +            if (getFence() > (i = index)) {
1459 +                index = i + 1;
1460 +                action.accept((E)array[i]);
1461 +                if (modCount != expectedModCount)
1462 +                    throw new ConcurrentModificationException();
1463 +                return true;
1464 +            }
1465 +            return false;
1466 +        }
1467 +
1468 +        @SuppressWarnings("unchecked")
1469 +        public void forEachRemaining(Consumer<? super E> action) {
1470 +            Objects.requireNonNull(action);
1471 +            final int hi = getFence();
1472 +            final Object[] a = array;
1473 +            int i;
1474 +            for (i = index, index = hi; i < hi; i++)
1475 +                action.accept((E) a[i]);
1476 +            if (modCount != expectedModCount)
1477 +                throw new ConcurrentModificationException();
1478 +        }
1479 +
1480 +        public long estimateSize() {
1481 +            return getFence() - index;
1482 +        }
1483 +
1484 +        public int characteristics() {
1485 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1486 +        }
1487 +    }
1488 +
1489 +    void checkInvariants() {
1490 +        // assert elementCount >= 0;
1491 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1492 +    }
1493   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines