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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines