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.23 by jsr166, Sun May 18 23:47:56 2008 UTC vs.
Revision 1.46 by jsr166, Sat May 6 06:49:46 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright 1994-2007 Sun Microsystems, Inc.  All Rights Reserved.
2 > * Copyright (c) 1994, 2013, 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.util.function.Consumer;
29 + import java.util.function.Predicate;
30 + import java.util.function.UnaryOperator;
31 +
32   /**
33   * The {@code Vector} class implements a growable array of
34   * objects. Like an array, it contains components that can be
# Line 41 | Line 45 | package java.util;
45   * capacity of a vector before inserting a large number of
46   * components; this reduces the amount of incremental reallocation.
47   *
48 < * <p><a name="fail-fast"/>
48 > * <p id="fail-fast">
49   * The iterators returned by this class's {@link #iterator() iterator} and
50   * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
51   * if the vector is structurally modified at any time after the iterator is
# Line 52 | Line 56 | package java.util;
56   * concurrent modification, the iterator fails quickly and cleanly, rather
57   * than risking arbitrary, non-deterministic behavior at an undetermined
58   * time in the future.  The {@link Enumeration Enumerations} returned by
59 < * the {@link #elements() elements} method are <em>not</em> fail-fast.
59 > * the {@link #elements() elements} method are <em>not</em> fail-fast; if the
60 > * Vector is structurally modified at any time after the enumeration is
61 > * created then the results of enumerating are undefined.
62   *
63   * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
64   * as it is, generally speaking, impossible to make any hard guarantees in the
# Line 64 | Line 70 | package java.util;
70   *
71   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
72   * implement the {@link List} interface, making it a member of the
73 < * <a href="{@docRoot}/../technotes/guides/collections/index.html"> Java
74 < * Collections Framework</a>.  Unlike the new collection
75 < * implementations, {@code Vector} is synchronized.
73 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
74 > * Java Collections Framework</a>.  Unlike the new collection
75 > * implementations, {@code Vector} is synchronized.  If a thread-safe
76 > * implementation is not needed, it is recommended to use {@link
77 > * ArrayList} in place of {@code Vector}.
78 > *
79 > * @param <E> Type of component elements
80   *
81   * @author  Lee Boynton
82   * @author  Jonathan Payne
73 * @version %I%, %G%
83   * @see Collection
75 * @see List
76 * @see ArrayList
84   * @see LinkedList
85 < * @since   JDK1.0
85 > * @since   1.0
86   */
87   public class Vector<E>
88      extends AbstractList<E>
# Line 167 | Line 174 | public class Vector<E>
174      public Vector(Collection<? extends E> c) {
175          elementData = c.toArray();
176          elementCount = elementData.length;
177 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
177 >        // defend against c.toArray (incorrectly) not returning Object[]
178 >        // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
179          if (elementData.getClass() != Object[].class)
180              elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
181      }
# Line 223 | Line 231 | public class Vector<E>
231       * @param minCapacity the desired minimum capacity
232       */
233      public synchronized void ensureCapacity(int minCapacity) {
234 <        modCount++;
235 <        ensureCapacityHelper(minCapacity);
234 >        if (minCapacity > 0) {
235 >            modCount++;
236 >            if (minCapacity > elementData.length)
237 >                grow(minCapacity);
238 >        }
239      }
240  
241      /**
242 <     * This implements the unsynchronized semantics of ensureCapacity.
243 <     * Synchronized methods in this class can internally call this
244 <     * method for ensuring capacity without incurring the cost of an
245 <     * extra synchronization.
242 >     * The maximum size of array to allocate (unless necessary).
243 >     * Some VMs reserve some header words in an array.
244 >     * Attempts to allocate larger arrays may result in
245 >     * OutOfMemoryError: Requested array size exceeds VM limit
246 >     */
247 >    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
248 >
249 >    /**
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 >        return elementData = Arrays.copyOf(elementData,
258 >                                           newCapacity(minCapacity));
259 >    }
260 >
261 >    private Object[] grow() {
262 >        return grow(elementCount + 1);
263 >    }
264 >
265 >    /**
266 >     * Returns a capacity at least as large as the given minimum capacity.
267 >     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
268 >     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
269 >     *
270 >     * @param minCapacity the desired minimum capacity
271 >     * @throws OutOfMemoryError if minCapacity is less than zero
272 >     */
273 >    private int newCapacity(int minCapacity) {
274 >        // overflow-conscious code
275          int oldCapacity = elementData.length;
276 <        if (minCapacity > oldCapacity) {
277 <            Object[] oldData = elementData;
278 <            int newCapacity = (capacityIncrement > 0) ?
279 <                (oldCapacity + capacityIncrement) : (oldCapacity * 2);
280 <            if (newCapacity < minCapacity) {
281 <                newCapacity = minCapacity;
282 <            }
283 <            elementData = Arrays.copyOf(elementData, newCapacity);
284 <        }
276 >        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
277 >                                         capacityIncrement : oldCapacity);
278 >        if (newCapacity - minCapacity <= 0) {
279 >            if (minCapacity < 0) // overflow
280 >                throw new OutOfMemoryError();
281 >            return minCapacity;
282 >        }
283 >        return (newCapacity - MAX_ARRAY_SIZE <= 0)
284 >            ? newCapacity
285 >            : hugeCapacity(minCapacity);
286 >    }
287 >
288 >    private static int hugeCapacity(int minCapacity) {
289 >        if (minCapacity < 0) // overflow
290 >            throw new OutOfMemoryError();
291 >        return (minCapacity > MAX_ARRAY_SIZE) ?
292 >            Integer.MAX_VALUE :
293 >            MAX_ARRAY_SIZE;
294      }
295  
296      /**
# Line 259 | Line 304 | public class Vector<E>
304       */
305      public synchronized void setSize(int newSize) {
306          modCount++;
307 <        if (newSize > elementCount) {
308 <            ensureCapacityHelper(newSize);
309 <        } else {
310 <            for (int i = newSize ; i < elementCount ; i++) {
311 <                elementData[i] = null;
267 <            }
268 <        }
307 >        if (newSize > elementData.length)
308 >            grow(newSize);
309 >        final Object[] es = elementData;
310 >        for (int to = elementCount, i = newSize; i < to; i++)
311 >            es[i] = null;
312          elementCount = newSize;
313      }
314  
# Line 304 | Line 347 | public class Vector<E>
347       * Returns an enumeration of the components of this vector. The
348       * returned {@code Enumeration} object will generate all items in
349       * this vector. The first item generated is the item at index {@code 0},
350 <     * then the item at index {@code 1}, and so on.
350 >     * then the item at index {@code 1}, and so on. If the vector is
351 >     * structurally modified while enumerating over the elements then the
352 >     * results of enumerating are undefined.
353       *
354       * @return  an enumeration of the components of this vector
355       * @see     Iterator
# Line 332 | Line 377 | public class Vector<E>
377       * Returns {@code true} if this vector contains the specified element.
378       * More formally, returns {@code true} if and only if this vector
379       * contains at least one element {@code e} such that
380 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
380 >     * {@code Objects.equals(o, e)}.
381       *
382       * @param o element whose presence in this vector is to be tested
383       * @return {@code true} if this vector contains the specified element
# Line 345 | Line 390 | public class Vector<E>
390       * Returns the index of the first occurrence of the specified element
391       * in this vector, or -1 if this vector does not contain the element.
392       * More formally, returns the lowest index {@code i} such that
393 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
393 >     * {@code Objects.equals(o, get(i))},
394       * or -1 if there is no such index.
395       *
396       * @param o element to search for
# Line 361 | Line 406 | public class Vector<E>
406       * this vector, searching forwards from {@code index}, or returns -1 if
407       * the element is not found.
408       * More formally, returns the lowest index {@code i} such that
409 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
409 >     * {@code (i >= index && Objects.equals(o, get(i)))},
410       * or -1 if there is no such index.
411       *
412       * @param o element to search for
# Line 389 | Line 434 | public class Vector<E>
434       * Returns the index of the last occurrence of the specified element
435       * in this vector, or -1 if this vector does not contain the element.
436       * More formally, returns the highest index {@code i} such that
437 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
437 >     * {@code Objects.equals(o, get(i))},
438       * or -1 if there is no such index.
439       *
440       * @param o element to search for
# Line 405 | Line 450 | public class Vector<E>
450       * this vector, searching backwards from {@code index}, or returns -1 if
451       * the element is not found.
452       * More formally, returns the highest index {@code i} such that
453 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
453 >     * {@code (i <= index && Objects.equals(o, get(i)))},
454       * or -1 if there is no such index.
455       *
456       * @param o element to search for
# Line 469 | Line 514 | public class Vector<E>
514       * Returns the last component of the vector.
515       *
516       * @return  the last component of the vector, i.e., the component at index
517 <     *          <code>size()&nbsp;-&nbsp;1</code>.
517 >     *          {@code size() - 1}
518       * @throws NoSuchElementException if this vector is empty
519       */
520      public synchronized E lastElement() {
# Line 527 | Line 572 | public class Vector<E>
572       *         ({@code index < 0 || index >= size()})
573       */
574      public synchronized void removeElementAt(int index) {
530        modCount++;
575          if (index >= elementCount) {
576              throw new ArrayIndexOutOfBoundsException(index + " >= " +
577                                                       elementCount);
# Line 539 | Line 583 | public class Vector<E>
583          if (j > 0) {
584              System.arraycopy(elementData, index + 1, elementData, index, j);
585          }
586 +        modCount++;
587          elementCount--;
588          elementData[elementCount] = null; /* to let gc do its work */
589 +        // checkInvariants();
590      }
591  
592      /**
# Line 567 | Line 613 | public class Vector<E>
613       *         ({@code index < 0 || index > size()})
614       */
615      public synchronized void insertElementAt(E obj, int index) {
570        modCount++;
616          if (index > elementCount) {
617              throw new ArrayIndexOutOfBoundsException(index
618                                                       + " > " + elementCount);
619          }
620 <        ensureCapacityHelper(elementCount + 1);
621 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
620 >        modCount++;
621 >        final int s = elementCount;
622 >        Object[] elementData = this.elementData;
623 >        if (s == elementData.length)
624 >            elementData = grow();
625 >        System.arraycopy(elementData, index,
626 >                         elementData, index + 1,
627 >                         s - index);
628          elementData[index] = obj;
629 <        elementCount++;
629 >        elementCount = s + 1;
630      }
631  
632      /**
# Line 591 | Line 642 | public class Vector<E>
642       */
643      public synchronized void addElement(E obj) {
644          modCount++;
645 <        ensureCapacityHelper(elementCount + 1);
595 <        elementData[elementCount++] = obj;
645 >        add(obj, elementData, elementCount);
646      }
647  
648      /**
# Line 627 | Line 677 | public class Vector<E>
677       * method (which is part of the {@link List} interface).
678       */
679      public synchronized void removeAllElements() {
680 +        final Object[] es = elementData;
681 +        for (int to = elementCount, i = elementCount = 0; i < to; i++)
682 +            es[i] = null;
683          modCount++;
631        // Let gc do its work
632        for (int i = 0; i < elementCount; i++)
633            elementData[i] = null;
634
635        elementCount = 0;
684      }
685  
686      /**
# Line 645 | Line 693 | public class Vector<E>
693      public synchronized Object clone() {
694          try {
695              @SuppressWarnings("unchecked")
696 <                Vector<E> v = (Vector<E>) super.clone();
696 >            Vector<E> v = (Vector<E>) super.clone();
697              v.elementData = Arrays.copyOf(elementData, elementCount);
698              v.modCount = 0;
699              return v;
700          } catch (CloneNotSupportedException e) {
701              // this shouldn't happen, since we are Cloneable
702 <            throw new InternalError();
702 >            throw new InternalError(e);
703          }
704      }
705  
# Line 679 | Line 727 | public class Vector<E>
727       * of the Vector <em>only</em> if the caller knows that the Vector
728       * does not contain any null elements.)
729       *
730 +     * @param <T> type of array elements. The same type as {@code <E>} or a
731 +     * supertype of {@code <E>}.
732       * @param a the array into which the elements of the Vector are to
733       *          be stored, if it is big enough; otherwise, a new array of the
734       *          same runtime type is allocated for this purpose.
735       * @return an array containing the elements of the Vector
736 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
737 <     * of the runtime type of every element in this Vector
736 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
737 >     * a supertype of the runtime type, {@code <E>}, of every element in this
738 >     * Vector
739       * @throws NullPointerException if the given array is null
740       * @since 1.2
741       */
# Line 708 | Line 759 | public class Vector<E>
759          return (E) elementData[index];
760      }
761  
762 +    @SuppressWarnings("unchecked")
763 +    static <E> E elementAt(Object[] es, int index) {
764 +        return (E) es[index];
765 +    }
766 +
767      /**
768       * Returns the element at the specified position in this Vector.
769       *
# Line 745 | Line 801 | public class Vector<E>
801      }
802  
803      /**
804 +     * This helper method split out from add(E) to keep method
805 +     * bytecode size under 35 (the -XX:MaxInlineSize default value),
806 +     * which helps when add(E) is called in a C1-compiled loop.
807 +     */
808 +    private void add(E e, Object[] elementData, int s) {
809 +        if (s == elementData.length)
810 +            elementData = grow();
811 +        elementData[s] = e;
812 +        elementCount = s + 1;
813 +        // checkInvariants();
814 +    }
815 +
816 +    /**
817       * Appends the specified element to the end of this Vector.
818       *
819       * @param e element to be appended to this Vector
# Line 753 | Line 822 | public class Vector<E>
822       */
823      public synchronized boolean add(E e) {
824          modCount++;
825 <        ensureCapacityHelper(elementCount + 1);
757 <        elementData[elementCount++] = e;
825 >        add(e, elementData, elementCount);
826          return true;
827      }
828  
# Line 762 | Line 830 | public class Vector<E>
830       * Removes the first occurrence of the specified element in this Vector
831       * If the Vector does not contain the element, it is unchanged.  More
832       * formally, removes the element with the lowest index i such that
833 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
833 >     * {@code Objects.equals(o, get(i))} (if such
834       * an element exists).
835       *
836       * @param o element to be removed from this Vector, if present
# Line 793 | Line 861 | public class Vector<E>
861       * Shifts any subsequent elements to the left (subtracts one from their
862       * indices).  Returns the element that was removed from the Vector.
863       *
796     * @throws ArrayIndexOutOfBoundsException if the index is out of range
797     *         ({@code index < 0 || index >= size()})
864       * @param index the index of the element to be removed
865       * @return element that was removed
866 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
867 +     *         ({@code index < 0 || index >= size()})
868       * @since 1.2
869       */
870      public synchronized E remove(int index) {
# Line 811 | Line 879 | public class Vector<E>
879                               numMoved);
880          elementData[--elementCount] = null; // Let gc do its work
881  
882 +        // checkInvariants();
883          return oldValue;
884      }
885  
# Line 853 | Line 922 | public class Vector<E>
922       * @throws NullPointerException if the specified collection is null
923       * @since 1.2
924       */
925 <    public synchronized boolean addAll(Collection<? extends E> c) {
857 <        modCount++;
925 >    public boolean addAll(Collection<? extends E> c) {
926          Object[] a = c.toArray();
927 +        modCount++;
928          int numNew = a.length;
929 <        ensureCapacityHelper(elementCount + numNew);
930 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
931 <        elementCount += numNew;
932 <        return numNew != 0;
929 >        if (numNew == 0)
930 >            return false;
931 >        synchronized (this) {
932 >            Object[] elementData = this.elementData;
933 >            final int s = elementCount;
934 >            if (numNew > elementData.length - s)
935 >                elementData = grow(s + numNew);
936 >            System.arraycopy(a, 0, elementData, s, numNew);
937 >            elementCount = s + numNew;
938 >            // checkInvariants();
939 >            return true;
940 >        }
941      }
942  
943      /**
# Line 871 | Line 948 | public class Vector<E>
948       * @return true if this Vector changed as a result of the call
949       * @throws ClassCastException if the types of one or more elements
950       *         in this vector are incompatible with the specified
951 <     *         collection (optional)
951 >     *         collection
952 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
953       * @throws NullPointerException if this vector contains one or more null
954       *         elements and the specified collection does not support null
955 <     *         elements (optional), or if the specified collection is null
955 >     *         elements
956 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
957 >     *         or if the specified collection is null
958       * @since 1.2
959       */
960 <    public synchronized boolean removeAll(Collection<?> c) {
961 <        return super.removeAll(c);
960 >    public boolean removeAll(Collection<?> c) {
961 >        Objects.requireNonNull(c);
962 >        return bulkRemove(e -> c.contains(e));
963      }
964  
965      /**
# Line 891 | Line 972 | public class Vector<E>
972       * @return true if this Vector changed as a result of the call
973       * @throws ClassCastException if the types of one or more elements
974       *         in this vector are incompatible with the specified
975 <     *         collection (optional)
975 >     *         collection
976 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
977       * @throws NullPointerException if this vector contains one or more null
978       *         elements and the specified collection does not support null
979 <     *         elements (optional), or if the specified collection is null
979 >     *         elements
980 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
981 >     *         or if the specified collection is null
982       * @since 1.2
983       */
984 <    public synchronized boolean retainAll(Collection<?> c)  {
985 <        return super.retainAll(c);
984 >    public boolean retainAll(Collection<?> c) {
985 >        Objects.requireNonNull(c);
986 >        return bulkRemove(e -> !c.contains(e));
987 >    }
988 >
989 >    /**
990 >     * @throws NullPointerException {@inheritDoc}
991 >     */
992 >    @Override
993 >    public boolean removeIf(Predicate<? super E> filter) {
994 >        Objects.requireNonNull(filter);
995 >        return bulkRemove(filter);
996 >    }
997 >
998 >    // A tiny bit set implementation
999 >
1000 >    private static long[] nBits(int n) {
1001 >        return new long[((n - 1) >> 6) + 1];
1002 >    }
1003 >    private static void setBit(long[] bits, int i) {
1004 >        bits[i >> 6] |= 1L << i;
1005 >    }
1006 >    private static boolean isClear(long[] bits, int i) {
1007 >        return (bits[i >> 6] & (1L << i)) == 0;
1008 >    }
1009 >
1010 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
1011 >        int expectedModCount = modCount;
1012 >        final Object[] es = elementData;
1013 >        final int end = elementCount;
1014 >        int i;
1015 >        // Optimize for initial run of survivors
1016 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
1017 >            ;
1018 >        // Tolerate predicates that reentrantly access the collection for
1019 >        // read (but writers still get CME), so traverse once to find
1020 >        // elements to delete, a second pass to physically expunge.
1021 >        if (i < end) {
1022 >            final int beg = i;
1023 >            final long[] deathRow = nBits(end - beg);
1024 >            deathRow[0] = 1L;   // set bit 0
1025 >            for (i = beg + 1; i < end; i++)
1026 >                if (filter.test(elementAt(es, i)))
1027 >                    setBit(deathRow, i - beg);
1028 >            if (modCount != expectedModCount)
1029 >                throw new ConcurrentModificationException();
1030 >            expectedModCount++;
1031 >            modCount++;
1032 >            int w = beg;
1033 >            for (i = beg; i < end; i++)
1034 >                if (isClear(deathRow, i - beg))
1035 >                    es[w++] = es[i];
1036 >            for (i = elementCount = w; i < end; i++)
1037 >                es[i] = null;
1038 >            // checkInvariants();
1039 >            return true;
1040 >        } else {
1041 >            if (modCount != expectedModCount)
1042 >                throw new ConcurrentModificationException();
1043 >            // checkInvariants();
1044 >            return false;
1045 >        }
1046      }
1047  
1048      /**
# Line 919 | Line 1063 | public class Vector<E>
1063       * @since 1.2
1064       */
1065      public synchronized boolean addAll(int index, Collection<? extends E> c) {
922        modCount++;
1066          if (index < 0 || index > elementCount)
1067              throw new ArrayIndexOutOfBoundsException(index);
1068  
1069          Object[] a = c.toArray();
1070 +        modCount++;
1071          int numNew = a.length;
1072 <        ensureCapacityHelper(elementCount + numNew);
1072 >        if (numNew == 0)
1073 >            return false;
1074 >        Object[] elementData = this.elementData;
1075 >        final int s = elementCount;
1076 >        if (numNew > elementData.length - s)
1077 >            elementData = grow(s + numNew);
1078  
1079 <        int numMoved = elementCount - index;
1079 >        int numMoved = s - index;
1080          if (numMoved > 0)
1081 <            System.arraycopy(elementData, index, elementData, index + numNew,
1081 >            System.arraycopy(elementData, index,
1082 >                             elementData, index + numNew,
1083                               numMoved);
934
1084          System.arraycopy(a, 0, elementData, index, numNew);
1085 <        elementCount += numNew;
1086 <        return numNew != 0;
1085 >        elementCount = s + numNew;
1086 >        // checkInvariants();
1087 >        return true;
1088      }
1089  
1090      /**
# Line 942 | Line 1092 | public class Vector<E>
1092       * true if and only if the specified Object is also a List, both Lists
1093       * have the same size, and all corresponding pairs of elements in the two
1094       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1095 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1096 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1095 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1096 >     * In other words, two Lists are defined to be
1097       * equal if they contain the same elements in the same order.
1098       *
1099       * @param o the Object to be compared for equality with this Vector
# Line 1016 | Line 1166 | public class Vector<E>
1166       */
1167      protected synchronized void removeRange(int fromIndex, int toIndex) {
1168          modCount++;
1169 <        int numMoved = elementCount - toIndex;
1170 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1171 <                         numMoved);
1169 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1170 >        // checkInvariants();
1171 >    }
1172  
1173 <        // Let gc do its work
1174 <        int newElementCount = elementCount - (toIndex-fromIndex);
1175 <        while (elementCount != newElementCount)
1176 <            elementData[--elementCount] = null;
1173 >    /** Erases the gap from lo to hi, by sliding down following elements. */
1174 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1175 >        System.arraycopy(es, hi, es, lo, elementCount - hi);
1176 >        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1177 >            es[i] = null;
1178      }
1179  
1180      /**
1181 <     * Save the state of the {@code Vector} instance to a stream (that
1182 <     * is, serialize it).  This method is present merely for synchronization.
1183 <     * It just calls the default writeObject method.
1181 >     * Saves the state of the {@code Vector} instance to a stream
1182 >     * (that is, serializes it).
1183 >     * This method performs synchronization to ensure the consistency
1184 >     * of the serialized data.
1185 >     *
1186 >     * @param s the stream
1187 >     * @throws java.io.IOException if an I/O error occurs
1188       */
1189 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1190 <        throws java.io.IOException
1191 <    {
1192 <        s.defaultWriteObject();
1189 >    private void writeObject(java.io.ObjectOutputStream s)
1190 >            throws java.io.IOException {
1191 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1192 >        final Object[] data;
1193 >        synchronized (this) {
1194 >            fields.put("capacityIncrement", capacityIncrement);
1195 >            fields.put("elementCount", elementCount);
1196 >            data = elementData.clone();
1197 >        }
1198 >        fields.put("elementData", data);
1199 >        s.writeFields();
1200      }
1201  
1202      /**
# Line 1115 | Line 1277 | public class Vector<E>
1277              lastRet = -1;
1278          }
1279  
1280 +        @Override
1281 +        public void forEachRemaining(Consumer<? super E> action) {
1282 +            Objects.requireNonNull(action);
1283 +            synchronized (Vector.this) {
1284 +                final int size = elementCount;
1285 +                int i = cursor;
1286 +                if (i >= size) {
1287 +                    return;
1288 +                }
1289 +                final Object[] es = elementData;
1290 +                if (i >= es.length)
1291 +                    throw new ConcurrentModificationException();
1292 +                while (i < size && modCount == expectedModCount)
1293 +                    action.accept(elementAt(es, i++));
1294 +                // update once at end of iteration to reduce heap write traffic
1295 +                cursor = i;
1296 +                lastRet = i - 1;
1297 +                checkForComodification();
1298 +            }
1299 +        }
1300 +
1301          final void checkForComodification() {
1302              if (modCount != expectedModCount)
1303                  throw new ConcurrentModificationException();
# Line 1173 | Line 1356 | public class Vector<E>
1356              lastRet = -1;
1357          }
1358      }
1359 +
1360 +    /**
1361 +     * @throws NullPointerException {@inheritDoc}
1362 +     */
1363 +    @Override
1364 +    public synchronized void forEach(Consumer<? super E> action) {
1365 +        Objects.requireNonNull(action);
1366 +        final int expectedModCount = modCount;
1367 +        final Object[] es = elementData;
1368 +        final int size = elementCount;
1369 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1370 +            action.accept(elementAt(es, i));
1371 +        if (modCount != expectedModCount)
1372 +            throw new ConcurrentModificationException();
1373 +        // checkInvariants();
1374 +    }
1375 +
1376 +    /**
1377 +     * @throws NullPointerException {@inheritDoc}
1378 +     */
1379 +    @Override
1380 +    public synchronized void replaceAll(UnaryOperator<E> operator) {
1381 +        Objects.requireNonNull(operator);
1382 +        final int expectedModCount = modCount;
1383 +        final Object[] es = elementData;
1384 +        final int size = elementCount;
1385 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1386 +            es[i] = operator.apply(elementAt(es, i));
1387 +        if (modCount != expectedModCount)
1388 +            throw new ConcurrentModificationException();
1389 +        modCount++;
1390 +        // checkInvariants();
1391 +    }
1392 +
1393 +    @SuppressWarnings("unchecked")
1394 +    @Override
1395 +    public synchronized void sort(Comparator<? super E> c) {
1396 +        final int expectedModCount = modCount;
1397 +        Arrays.sort((E[]) elementData, 0, elementCount, c);
1398 +        if (modCount != expectedModCount)
1399 +            throw new ConcurrentModificationException();
1400 +        modCount++;
1401 +        // checkInvariants();
1402 +    }
1403 +
1404 +    /**
1405 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1406 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1407 +     * list.
1408 +     *
1409 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1410 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1411 +     * Overriding implementations should document the reporting of additional
1412 +     * characteristic values.
1413 +     *
1414 +     * @return a {@code Spliterator} over the elements in this list
1415 +     * @since 1.8
1416 +     */
1417 +    @Override
1418 +    public Spliterator<E> spliterator() {
1419 +        return new VectorSpliterator(null, 0, -1, 0);
1420 +    }
1421 +
1422 +    /** Similar to ArrayList Spliterator */
1423 +    final class VectorSpliterator implements Spliterator<E> {
1424 +        private Object[] array;
1425 +        private int index; // current index, modified on advance/split
1426 +        private int fence; // -1 until used; then one past last index
1427 +        private int expectedModCount; // initialized when fence set
1428 +
1429 +        /** Creates new spliterator covering the given range. */
1430 +        VectorSpliterator(Object[] array, int origin, int fence,
1431 +                          int expectedModCount) {
1432 +            this.array = array;
1433 +            this.index = origin;
1434 +            this.fence = fence;
1435 +            this.expectedModCount = expectedModCount;
1436 +        }
1437 +
1438 +        private int getFence() { // initialize on first use
1439 +            int hi;
1440 +            if ((hi = fence) < 0) {
1441 +                synchronized (Vector.this) {
1442 +                    array = elementData;
1443 +                    expectedModCount = modCount;
1444 +                    hi = fence = elementCount;
1445 +                }
1446 +            }
1447 +            return hi;
1448 +        }
1449 +
1450 +        public Spliterator<E> trySplit() {
1451 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1452 +            return (lo >= mid) ? null :
1453 +                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1454 +        }
1455 +
1456 +        @SuppressWarnings("unchecked")
1457 +        public boolean tryAdvance(Consumer<? super E> action) {
1458 +            Objects.requireNonNull(action);
1459 +            int i;
1460 +            if (getFence() > (i = index)) {
1461 +                index = i + 1;
1462 +                action.accept((E)array[i]);
1463 +                if (modCount != expectedModCount)
1464 +                    throw new ConcurrentModificationException();
1465 +                return true;
1466 +            }
1467 +            return false;
1468 +        }
1469 +
1470 +        @SuppressWarnings("unchecked")
1471 +        public void forEachRemaining(Consumer<? super E> action) {
1472 +            Objects.requireNonNull(action);
1473 +            final int hi = getFence();
1474 +            final Object[] a = array;
1475 +            int i;
1476 +            for (i = index, index = hi; i < hi; i++)
1477 +                action.accept((E) a[i]);
1478 +            if (modCount != expectedModCount)
1479 +                throw new ConcurrentModificationException();
1480 +        }
1481 +
1482 +        public long estimateSize() {
1483 +            return getFence() - index;
1484 +        }
1485 +
1486 +        public int characteristics() {
1487 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1488 +        }
1489 +    }
1490 +
1491 +    void checkInvariants() {
1492 +        // assert elementCount >= 0;
1493 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1494 +    }
1495   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines