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.38 by jsr166, Thu Dec 1 00:35:21 2016 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}/../technotes/guides/collections/index.html">
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 >     * 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 >     * @param minCapacity the desired minimum capacity
254 >     * @throws OutOfMemoryError if minCapacity is less than zero
255 >     */
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 <     * This implements the unsynchronized semantics of ensureCapacity.
267 <     * Synchronized methods in this class can internally call this
268 <     * method for ensuring capacity without incurring the cost of an
234 <     * extra synchronization.
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 <     * @see #ensureCapacity(int)
270 >     * @param minCapacity the desired minimum capacity
271 >     * @throws OutOfMemoryError if minCapacity is less than zero
272       */
273 <    private void ensureCapacityHelper(int minCapacity) {
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++) {
266 <                elementData[i] = null;
267 <            }
268 <        }
307 >        if (newSize > elementData.length)
308 >            grow(newSize);
309 >        for (int i = newSize; i < elementCount; i++)
310 >            elementData[i] = null;
311          elementCount = newSize;
312      }
313  
# Line 304 | Line 346 | public class Vector<E>
346       * Returns an enumeration of the components of this vector. The
347       * returned {@code Enumeration} object will generate all items in
348       * this vector. The first item generated is the item at index {@code 0},
349 <     * then the item at index {@code 1}, and so on.
349 >     * then the item at index {@code 1}, and so on. If the vector is
350 >     * structurally modified while enumerating over the elements then the
351 >     * results of enumerating are undefined.
352       *
353       * @return  an enumeration of the components of this vector
354       * @see     Iterator
# Line 332 | Line 376 | public class Vector<E>
376       * Returns {@code true} if this vector contains the specified element.
377       * More formally, returns {@code true} if and only if this vector
378       * contains at least one element {@code e} such that
379 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
379 >     * {@code Objects.equals(o, e)}.
380       *
381       * @param o element whose presence in this vector is to be tested
382       * @return {@code true} if this vector contains the specified element
# Line 345 | Line 389 | public class Vector<E>
389       * Returns the index of the first occurrence of the specified element
390       * in this vector, or -1 if this vector does not contain the element.
391       * More formally, returns the lowest index {@code i} such that
392 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
392 >     * {@code Objects.equals(o, get(i))},
393       * or -1 if there is no such index.
394       *
395       * @param o element to search for
# Line 361 | Line 405 | public class Vector<E>
405       * this vector, searching forwards from {@code index}, or returns -1 if
406       * the element is not found.
407       * More formally, returns the lowest index {@code i} such that
408 <     * <tt>(i&nbsp;&gt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
408 >     * {@code (i >= index && Objects.equals(o, get(i)))},
409       * or -1 if there is no such index.
410       *
411       * @param o element to search for
# Line 389 | Line 433 | public class Vector<E>
433       * Returns the index of the last occurrence of the specified element
434       * in this vector, or -1 if this vector does not contain the element.
435       * More formally, returns the highest index {@code i} such that
436 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
436 >     * {@code Objects.equals(o, get(i))},
437       * or -1 if there is no such index.
438       *
439       * @param o element to search for
# Line 405 | Line 449 | public class Vector<E>
449       * this vector, searching backwards from {@code index}, or returns -1 if
450       * the element is not found.
451       * More formally, returns the highest index {@code i} such that
452 <     * <tt>(i&nbsp;&lt;=&nbsp;index&nbsp;&amp;&amp;&nbsp;(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i))))</tt>,
452 >     * {@code (i <= index && Objects.equals(o, get(i)))},
453       * or -1 if there is no such index.
454       *
455       * @param o element to search for
# Line 469 | Line 513 | public class Vector<E>
513       * Returns the last component of the vector.
514       *
515       * @return  the last component of the vector, i.e., the component at index
516 <     *          <code>size()&nbsp;-&nbsp;1</code>.
516 >     *          {@code size() - 1}
517       * @throws NoSuchElementException if this vector is empty
518       */
519      public synchronized E lastElement() {
# Line 527 | Line 571 | public class Vector<E>
571       *         ({@code index < 0 || index >= size()})
572       */
573      public synchronized void removeElementAt(int index) {
530        modCount++;
574          if (index >= elementCount) {
575              throw new ArrayIndexOutOfBoundsException(index + " >= " +
576                                                       elementCount);
# Line 539 | Line 582 | public class Vector<E>
582          if (j > 0) {
583              System.arraycopy(elementData, index + 1, elementData, index, j);
584          }
585 +        modCount++;
586          elementCount--;
587          elementData[elementCount] = null; /* to let gc do its work */
588 +        // checkInvariants();
589      }
590  
591      /**
# Line 567 | Line 612 | public class Vector<E>
612       *         ({@code index < 0 || index > size()})
613       */
614      public synchronized void insertElementAt(E obj, int index) {
570        modCount++;
615          if (index > elementCount) {
616              throw new ArrayIndexOutOfBoundsException(index
617                                                       + " > " + elementCount);
618          }
619 <        ensureCapacityHelper(elementCount + 1);
620 <        System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
619 >        modCount++;
620 >        final int s = elementCount;
621 >        Object[] elementData = this.elementData;
622 >        if (s == elementData.length)
623 >            elementData = grow();
624 >        System.arraycopy(elementData, index,
625 >                         elementData, index + 1,
626 >                         s - index);
627          elementData[index] = obj;
628 <        elementCount++;
628 >        elementCount = s + 1;
629      }
630  
631      /**
# Line 591 | Line 641 | public class Vector<E>
641       */
642      public synchronized void addElement(E obj) {
643          modCount++;
644 <        ensureCapacityHelper(elementCount + 1);
595 <        elementData[elementCount++] = obj;
644 >        add(obj, elementData, elementCount);
645      }
646  
647      /**
# Line 627 | Line 676 | public class Vector<E>
676       * method (which is part of the {@link List} interface).
677       */
678      public synchronized void removeAllElements() {
679 +        Arrays.fill(elementData, 0, elementCount, null);
680          modCount++;
631        // Let gc do its work
632        for (int i = 0; i < elementCount; i++)
633            elementData[i] = null;
634
681          elementCount = 0;
682      }
683  
# Line 645 | Line 691 | public class Vector<E>
691      public synchronized Object clone() {
692          try {
693              @SuppressWarnings("unchecked")
694 <                Vector<E> v = (Vector<E>) super.clone();
694 >            Vector<E> v = (Vector<E>) super.clone();
695              v.elementData = Arrays.copyOf(elementData, elementCount);
696              v.modCount = 0;
697              return v;
698          } catch (CloneNotSupportedException e) {
699              // this shouldn't happen, since we are Cloneable
700 <            throw new InternalError();
700 >            throw new InternalError(e);
701          }
702      }
703  
# Line 679 | Line 725 | public class Vector<E>
725       * of the Vector <em>only</em> if the caller knows that the Vector
726       * does not contain any null elements.)
727       *
728 +     * @param <T> type of array elements. The same type as {@code <E>} or a
729 +     * supertype of {@code <E>}.
730       * @param a the array into which the elements of the Vector are to
731       *          be stored, if it is big enough; otherwise, a new array of the
732       *          same runtime type is allocated for this purpose.
733       * @return an array containing the elements of the Vector
734 <     * @throws ArrayStoreException if the runtime type of a is not a supertype
735 <     * of the runtime type of every element in this Vector
734 >     * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
735 >     * a supertype of the runtime type, {@code <E>}, of every element in this
736 >     * Vector
737       * @throws NullPointerException if the given array is null
738       * @since 1.2
739       */
# Line 708 | Line 757 | public class Vector<E>
757          return (E) elementData[index];
758      }
759  
760 +    @SuppressWarnings("unchecked")
761 +    static <E> E elementAt(Object[] es, int index) {
762 +        return (E) es[index];
763 +    }
764 +
765      /**
766       * Returns the element at the specified position in this Vector.
767       *
# Line 745 | Line 799 | public class Vector<E>
799      }
800  
801      /**
802 +     * This helper method split out from add(E) to keep method
803 +     * bytecode size under 35 (the -XX:MaxInlineSize default value),
804 +     * which helps when add(E) is called in a C1-compiled loop.
805 +     */
806 +    private void add(E e, Object[] elementData, int s) {
807 +        if (s == elementData.length)
808 +            elementData = grow();
809 +        elementData[s] = e;
810 +        elementCount = s + 1;
811 +        // checkInvariants();
812 +    }
813 +
814 +    /**
815       * Appends the specified element to the end of this Vector.
816       *
817       * @param e element to be appended to this Vector
# Line 753 | Line 820 | public class Vector<E>
820       */
821      public synchronized boolean add(E e) {
822          modCount++;
823 <        ensureCapacityHelper(elementCount + 1);
757 <        elementData[elementCount++] = e;
823 >        add(e, elementData, elementCount);
824          return true;
825      }
826  
# Line 762 | Line 828 | public class Vector<E>
828       * Removes the first occurrence of the specified element in this Vector
829       * If the Vector does not contain the element, it is unchanged.  More
830       * formally, removes the element with the lowest index i such that
831 <     * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such
831 >     * {@code Objects.equals(o, get(i))} (if such
832       * an element exists).
833       *
834       * @param o element to be removed from this Vector, if present
# Line 793 | Line 859 | public class Vector<E>
859       * Shifts any subsequent elements to the left (subtracts one from their
860       * indices).  Returns the element that was removed from the Vector.
861       *
796     * @throws ArrayIndexOutOfBoundsException if the index is out of range
797     *         ({@code index < 0 || index >= size()})
862       * @param index the index of the element to be removed
863       * @return element that was removed
864 +     * @throws ArrayIndexOutOfBoundsException if the index is out of range
865 +     *         ({@code index < 0 || index >= size()})
866       * @since 1.2
867       */
868      public synchronized E remove(int index) {
# Line 811 | Line 877 | public class Vector<E>
877                               numMoved);
878          elementData[--elementCount] = null; // Let gc do its work
879  
880 +        // checkInvariants();
881          return oldValue;
882      }
883  
# Line 853 | Line 920 | public class Vector<E>
920       * @throws NullPointerException if the specified collection is null
921       * @since 1.2
922       */
923 <    public synchronized boolean addAll(Collection<? extends E> c) {
857 <        modCount++;
923 >    public boolean addAll(Collection<? extends E> c) {
924          Object[] a = c.toArray();
925 +        modCount++;
926          int numNew = a.length;
927 <        ensureCapacityHelper(elementCount + numNew);
928 <        System.arraycopy(a, 0, elementData, elementCount, numNew);
929 <        elementCount += numNew;
930 <        return numNew != 0;
927 >        if (numNew == 0)
928 >            return false;
929 >        synchronized (this) {
930 >            Object[] elementData = this.elementData;
931 >            final int s = elementCount;
932 >            if (numNew > elementData.length - s)
933 >                elementData = grow(s + numNew);
934 >            System.arraycopy(a, 0, elementData, s, numNew);
935 >            elementCount = s + numNew;
936 >            // checkInvariants();
937 >            return true;
938 >        }
939      }
940  
941      /**
# Line 871 | Line 946 | public class Vector<E>
946       * @return true if this Vector changed as a result of the call
947       * @throws ClassCastException if the types of one or more elements
948       *         in this vector are incompatible with the specified
949 <     *         collection (optional)
949 >     *         collection
950 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
951       * @throws NullPointerException if this vector contains one or more null
952       *         elements and the specified collection does not support null
953 <     *         elements (optional), or if the specified collection is null
953 >     *         elements
954 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
955 >     *         or if the specified collection is null
956       * @since 1.2
957       */
958 <    public synchronized boolean removeAll(Collection<?> c) {
959 <        return super.removeAll(c);
958 >    public boolean removeAll(Collection<?> c) {
959 >        Objects.requireNonNull(c);
960 >        return bulkRemove(e -> c.contains(e));
961      }
962  
963      /**
# Line 891 | Line 970 | public class Vector<E>
970       * @return true if this Vector changed as a result of the call
971       * @throws ClassCastException if the types of one or more elements
972       *         in this vector are incompatible with the specified
973 <     *         collection (optional)
973 >     *         collection
974 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
975       * @throws NullPointerException if this vector contains one or more null
976       *         elements and the specified collection does not support null
977 <     *         elements (optional), or if the specified collection is null
977 >     *         elements
978 >     *         (<a href="Collection.html#optional-restrictions">optional</a>),
979 >     *         or if the specified collection is null
980       * @since 1.2
981       */
982 <    public synchronized boolean retainAll(Collection<?> c)  {
983 <        return super.retainAll(c);
982 >    public boolean retainAll(Collection<?> c) {
983 >        Objects.requireNonNull(c);
984 >        return bulkRemove(e -> !c.contains(e));
985 >    }
986 >
987 >    @Override
988 >    public boolean removeIf(Predicate<? super E> filter) {
989 >        Objects.requireNonNull(filter);
990 >        return bulkRemove(filter);
991 >    }
992 >
993 >    // A tiny bit set implementation
994 >
995 >    private static long[] nBits(int n) {
996 >        return new long[((n - 1) >> 6) + 1];
997 >    }
998 >    private static void setBit(long[] bits, int i) {
999 >        bits[i >> 6] |= 1L << i;
1000 >    }
1001 >    private static boolean isClear(long[] bits, int i) {
1002 >        return (bits[i >> 6] & (1L << i)) == 0;
1003 >    }
1004 >
1005 >    private synchronized boolean bulkRemove(Predicate<? super E> filter) {
1006 >        int expectedModCount = modCount;
1007 >        final Object[] es = elementData;
1008 >        final int end = elementCount;
1009 >        int i;
1010 >        // Optimize for initial run of survivors
1011 >        for (i = 0; i < end && !filter.test(elementAt(es, i)); i++)
1012 >            ;
1013 >        // Tolerate predicates that reentrantly access the collection for
1014 >        // read (but writers still get CME), so traverse once to find
1015 >        // elements to delete, a second pass to physically expunge.
1016 >        if (i < end) {
1017 >            final int beg = i;
1018 >            final long[] deathRow = nBits(end - beg);
1019 >            deathRow[0] = 1L;   // set bit 0
1020 >            for (i = beg + 1; i < end; i++)
1021 >                if (filter.test(elementAt(es, i)))
1022 >                    setBit(deathRow, i - beg);
1023 >            if (modCount != expectedModCount)
1024 >                throw new ConcurrentModificationException();
1025 >            expectedModCount++;
1026 >            modCount++;
1027 >            int w = beg;
1028 >            for (i = beg; i < end; i++)
1029 >                if (isClear(deathRow, i - beg))
1030 >                    es[w++] = es[i];
1031 >            Arrays.fill(es, elementCount = w, end, null);
1032 >            // checkInvariants();
1033 >            return true;
1034 >        } else {
1035 >            if (modCount != expectedModCount)
1036 >                throw new ConcurrentModificationException();
1037 >            // checkInvariants();
1038 >            return false;
1039 >        }
1040      }
1041  
1042      /**
# Line 919 | Line 1057 | public class Vector<E>
1057       * @since 1.2
1058       */
1059      public synchronized boolean addAll(int index, Collection<? extends E> c) {
922        modCount++;
1060          if (index < 0 || index > elementCount)
1061              throw new ArrayIndexOutOfBoundsException(index);
1062  
1063          Object[] a = c.toArray();
1064 +        modCount++;
1065          int numNew = a.length;
1066 <        ensureCapacityHelper(elementCount + numNew);
1066 >        if (numNew == 0)
1067 >            return false;
1068 >        Object[] elementData = this.elementData;
1069 >        final int s = elementCount;
1070 >        if (numNew > elementData.length - s)
1071 >            elementData = grow(s + numNew);
1072  
1073 <        int numMoved = elementCount - index;
1073 >        int numMoved = s - index;
1074          if (numMoved > 0)
1075 <            System.arraycopy(elementData, index, elementData, index + numNew,
1075 >            System.arraycopy(elementData, index,
1076 >                             elementData, index + numNew,
1077                               numMoved);
934
1078          System.arraycopy(a, 0, elementData, index, numNew);
1079 <        elementCount += numNew;
1080 <        return numNew != 0;
1079 >        elementCount = s + numNew;
1080 >        // checkInvariants();
1081 >        return true;
1082      }
1083  
1084      /**
# Line 942 | Line 1086 | public class Vector<E>
1086       * true if and only if the specified Object is also a List, both Lists
1087       * have the same size, and all corresponding pairs of elements in the two
1088       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1089 <     * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :
1090 <     * e1.equals(e2))}.)  In other words, two Lists are defined to be
1089 >     * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1090 >     * In other words, two Lists are defined to be
1091       * equal if they contain the same elements in the same order.
1092       *
1093       * @param o the Object to be compared for equality with this Vector
# Line 1015 | Line 1159 | public class Vector<E>
1159       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1160       */
1161      protected synchronized void removeRange(int fromIndex, int toIndex) {
1162 +        final Object[] es = elementData;
1163 +        final int oldSize = elementCount;
1164 +        System.arraycopy(es, toIndex, es, fromIndex, oldSize - toIndex);
1165 +
1166          modCount++;
1167 <        int numMoved = elementCount - toIndex;
1168 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
1021 <                         numMoved);
1022 <
1023 <        // Let gc do its work
1024 <        int newElementCount = elementCount - (toIndex-fromIndex);
1025 <        while (elementCount != newElementCount)
1026 <            elementData[--elementCount] = null;
1167 >        Arrays.fill(es, elementCount -= (toIndex - fromIndex), oldSize, null);
1168 >        // checkInvariants();
1169      }
1170  
1171      /**
1172       * Save the state of the {@code Vector} instance to a stream (that
1173 <     * is, serialize it).  This method is present merely for synchronization.
1174 <     * It just calls the default writeObject method.
1175 <     */
1176 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
1177 <        throws java.io.IOException
1178 <    {
1179 <        s.defaultWriteObject();
1173 >     * is, serialize it).
1174 >     * This method performs synchronization to ensure the consistency
1175 >     * of the serialized data.
1176 >     */
1177 >    private void writeObject(java.io.ObjectOutputStream s)
1178 >            throws java.io.IOException {
1179 >        final java.io.ObjectOutputStream.PutField fields = s.putFields();
1180 >        final Object[] data;
1181 >        synchronized (this) {
1182 >            fields.put("capacityIncrement", capacityIncrement);
1183 >            fields.put("elementCount", elementCount);
1184 >            data = elementData.clone();
1185 >        }
1186 >        fields.put("elementData", data);
1187 >        s.writeFields();
1188      }
1189  
1190      /**
# Line 1115 | Line 1265 | public class Vector<E>
1265              lastRet = -1;
1266          }
1267  
1268 +        @Override
1269 +        public void forEachRemaining(Consumer<? super E> action) {
1270 +            Objects.requireNonNull(action);
1271 +            synchronized (Vector.this) {
1272 +                final int size = elementCount;
1273 +                int i = cursor;
1274 +                if (i >= size) {
1275 +                    return;
1276 +                }
1277 +                final Object[] es = elementData;
1278 +                if (i >= es.length)
1279 +                    throw new ConcurrentModificationException();
1280 +                while (i < size && modCount == expectedModCount)
1281 +                    action.accept(elementAt(es, i++));
1282 +                // update once at end of iteration to reduce heap write traffic
1283 +                cursor = i;
1284 +                lastRet = i - 1;
1285 +                checkForComodification();
1286 +            }
1287 +        }
1288 +
1289          final void checkForComodification() {
1290              if (modCount != expectedModCount)
1291                  throw new ConcurrentModificationException();
# Line 1173 | Line 1344 | public class Vector<E>
1344              lastRet = -1;
1345          }
1346      }
1347 +
1348 +    @Override
1349 +    public synchronized void forEach(Consumer<? super E> action) {
1350 +        Objects.requireNonNull(action);
1351 +        final int expectedModCount = modCount;
1352 +        final Object[] es = elementData;
1353 +        final int size = elementCount;
1354 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1355 +            action.accept(elementAt(es, i));
1356 +        if (modCount != expectedModCount)
1357 +            throw new ConcurrentModificationException();
1358 +        // checkInvariants();
1359 +    }
1360 +
1361 +    @Override
1362 +    public synchronized void replaceAll(UnaryOperator<E> operator) {
1363 +        Objects.requireNonNull(operator);
1364 +        final int expectedModCount = modCount;
1365 +        final Object[] es = elementData;
1366 +        final int size = elementCount;
1367 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1368 +            es[i] = operator.apply(elementAt(es, i));
1369 +        if (modCount != expectedModCount)
1370 +            throw new ConcurrentModificationException();
1371 +        modCount++;
1372 +        // checkInvariants();
1373 +    }
1374 +
1375 +    @SuppressWarnings("unchecked")
1376 +    @Override
1377 +    public synchronized void sort(Comparator<? super E> c) {
1378 +        final int expectedModCount = modCount;
1379 +        Arrays.sort((E[]) elementData, 0, elementCount, c);
1380 +        if (modCount != expectedModCount)
1381 +            throw new ConcurrentModificationException();
1382 +        modCount++;
1383 +        // checkInvariants();
1384 +    }
1385 +
1386 +    /**
1387 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1388 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1389 +     * list.
1390 +     *
1391 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1392 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1393 +     * Overriding implementations should document the reporting of additional
1394 +     * characteristic values.
1395 +     *
1396 +     * @return a {@code Spliterator} over the elements in this list
1397 +     * @since 1.8
1398 +     */
1399 +    @Override
1400 +    public Spliterator<E> spliterator() {
1401 +        return new VectorSpliterator(null, 0, -1, 0);
1402 +    }
1403 +
1404 +    /** Similar to ArrayList Spliterator */
1405 +    final class VectorSpliterator implements Spliterator<E> {
1406 +        private Object[] array;
1407 +        private int index; // current index, modified on advance/split
1408 +        private int fence; // -1 until used; then one past last index
1409 +        private int expectedModCount; // initialized when fence set
1410 +
1411 +        /** Create new spliterator covering the given range */
1412 +        VectorSpliterator(Object[] array, int origin, int fence,
1413 +                          int expectedModCount) {
1414 +            this.array = array;
1415 +            this.index = origin;
1416 +            this.fence = fence;
1417 +            this.expectedModCount = expectedModCount;
1418 +        }
1419 +
1420 +        private int getFence() { // initialize on first use
1421 +            int hi;
1422 +            if ((hi = fence) < 0) {
1423 +                synchronized (Vector.this) {
1424 +                    array = elementData;
1425 +                    expectedModCount = modCount;
1426 +                    hi = fence = elementCount;
1427 +                }
1428 +            }
1429 +            return hi;
1430 +        }
1431 +
1432 +        public Spliterator<E> trySplit() {
1433 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1434 +            return (lo >= mid) ? null :
1435 +                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1436 +        }
1437 +
1438 +        @SuppressWarnings("unchecked")
1439 +        public boolean tryAdvance(Consumer<? super E> action) {
1440 +            int i;
1441 +            if (action == null)
1442 +                throw new NullPointerException();
1443 +            if (getFence() > (i = index)) {
1444 +                index = i + 1;
1445 +                action.accept((E)array[i]);
1446 +                if (modCount != expectedModCount)
1447 +                    throw new ConcurrentModificationException();
1448 +                return true;
1449 +            }
1450 +            return false;
1451 +        }
1452 +
1453 +        @SuppressWarnings("unchecked")
1454 +        public void forEachRemaining(Consumer<? super E> action) {
1455 +            if (action == null)
1456 +                throw new NullPointerException();
1457 +            final int hi = getFence();
1458 +            final Object[] a = array;
1459 +            int i;
1460 +            for (i = index, index = hi; i < hi; i++)
1461 +                action.accept((E) a[i]);
1462 +            if (modCount != expectedModCount)
1463 +                throw new ConcurrentModificationException();
1464 +        }
1465 +
1466 +        public long estimateSize() {
1467 +            return getFence() - index;
1468 +        }
1469 +
1470 +        public int characteristics() {
1471 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1472 +        }
1473 +    }
1474 +
1475 +    void checkInvariants() {
1476 +        // assert elementCount >= 0;
1477 +        // assert elementCount == elementData.length || elementData[elementCount] == null;
1478 +    }
1479   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines