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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines