[cvs] / jsr166 / src / main / java / util / Vector.java Repository:
ViewVC logotype

Diff of /jsr166/src/main/java/util/Vector.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.29, Sat May 7 12:22:03 2011 UTC revision 1.30, Thu Nov 3 20:49:07 2016 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (c) 1994, 2008, Oracle and/or its affiliates. All rights reserved.   * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.   * 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   * 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   * under the terms of the GNU General Public License version 2 only, as
7   * published by the Free Software Foundation.  Sun designates this   * published by the Free Software Foundation.  Oracle designates this
8   * particular file as subject to the "Classpath" exception as provided   * particular file as subject to the "Classpath" exception as provided
9   * by Sun in the LICENSE file that accompanied this code.   * 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   * 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   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# Line 25  Line 25 
25    
26  package java.util;  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   * The {@code Vector} class implements a growable array of
34   * objects. Like an array, it contains components that can be   * objects. Like an array, it contains components that can be
# Line 41  Line 45 
45   * capacity of a vector before inserting a large number of   * capacity of a vector before inserting a large number of
46   * components; this reduces the amount of incremental reallocation.   * components; this reduces the amount of incremental reallocation.
47   *   *
48   * <p><a name="fail-fast"/>   * <p id="fail-fast">
49   * The iterators returned by this class's {@link #iterator() iterator} and   * The iterators returned by this class's {@link #iterator() iterator} and
50   * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:   * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
51   * if the vector is structurally modified at any time after the iterator is   * if the vector is structurally modified at any time after the iterator is
# Line 52  Line 56 
56   * concurrent modification, the iterator fails quickly and cleanly, rather   * concurrent modification, the iterator fails quickly and cleanly, rather
57   * than risking arbitrary, non-deterministic behavior at an undetermined   * than risking arbitrary, non-deterministic behavior at an undetermined
58   * time in the future.  The {@link Enumeration Enumerations} returned by   * time in the future.  The {@link Enumeration Enumerations} returned by
59   * the {@link #elements() elements} method are <em>not</em> fail-fast.   * 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   * <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   * as it is, generally speaking, impossible to make any hard guarantees in the
# Line 70  Line 76 
76   * implementation is not needed, it is recommended to use {@link   * implementation is not needed, it is recommended to use {@link
77   * ArrayList} in place of {@code Vector}.   * ArrayList} in place of {@code Vector}.
78   *   *
79     * @param <E> Type of component elements
80     *
81   * @author  Lee Boynton   * @author  Lee Boynton
82   * @author  Jonathan Payne   * @author  Jonathan Payne
83   * @see Collection   * @see Collection
84   * @see LinkedList   * @see LinkedList
85   * @since   JDK1.0   * @since   1.0
86   */   */
87  public class Vector<E>  public class Vector<E>
88      extends AbstractList<E>      extends AbstractList<E>
# Line 166  Line 174 
174      public Vector(Collection<? extends E> c) {      public Vector(Collection<? extends E> c) {
175          elementData = c.toArray();          elementData = c.toArray();
176          elementCount = elementData.length;          elementCount = elementData.length;
177          // c.toArray might (incorrectly) not return Object[] (see 6260652)          // 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)          if (elementData.getClass() != Object[].class)
180              elementData = Arrays.copyOf(elementData, elementCount, Object[].class);              elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
181      }      }
# Line 222  Line 231 
231       * @param minCapacity the desired minimum capacity       * @param minCapacity the desired minimum capacity
232       */       */
233      public synchronized void ensureCapacity(int minCapacity) {      public synchronized void ensureCapacity(int minCapacity) {
234            if (minCapacity > 0) {
235          modCount++;          modCount++;
236          ensureCapacityHelper(minCapacity);              if (minCapacity > elementData.length)
237                    grow(minCapacity);
238            }
239      }      }
240    
241      /**      /**
242       * This implements the unsynchronized semantics of ensureCapacity.       * The maximum size of array to allocate (unless necessary).
243       * Synchronized methods in this class can internally call this       * Some VMs reserve some header words in an array.
244       * method for ensuring capacity without incurring the cost of an       * Attempts to allocate larger arrays may result in
245       * extra synchronization.       * 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)       * @param minCapacity the desired minimum capacity
254         * @throws OutOfMemoryError if minCapacity is less than zero
255       */       */
256      private void ensureCapacityHelper(int minCapacity) {      private Object[] grow(int minCapacity) {
257          int oldCapacity = elementData.length;          return elementData = Arrays.copyOf(elementData,
258          if (minCapacity > oldCapacity) {                                             newCapacity(minCapacity));
             Object[] oldData = elementData;  
             int newCapacity = (capacityIncrement > 0) ?  
                 (oldCapacity + capacityIncrement) : (oldCapacity * 2);  
             if (newCapacity < minCapacity) {  
                 newCapacity = minCapacity;  
259              }              }
260              elementData = Arrays.copyOf(elementData, newCapacity);  
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            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 258  Line 304 
304       */       */
305      public synchronized void setSize(int newSize) {      public synchronized void setSize(int newSize) {
306          modCount++;          modCount++;
307          if (newSize > elementCount) {          if (newSize > elementData.length)
308              ensureCapacityHelper(newSize);              grow(newSize);
309          } else {          for (int i = newSize; i < elementCount; i++)
             for (int i = newSize ; i < elementCount ; i++) {  
310                  elementData[i] = null;                  elementData[i] = null;
             }  
         }  
311          elementCount = newSize;          elementCount = newSize;
312      }      }
313    
# Line 303  Line 346 
346       * Returns an enumeration of the components of this vector. The       * Returns an enumeration of the components of this vector. The
347       * returned {@code Enumeration} object will generate all items in       * returned {@code Enumeration} object will generate all items in
348       * this vector. The first item generated is the item at index {@code 0},       * this vector. The first item generated is the item at index {@code 0},
349       * then the item at index {@code 1}, and so on.       * 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       * @return  an enumeration of the components of this vector
354       * @see     Iterator       * @see     Iterator
# Line 331  Line 376 
376       * Returns {@code true} if this vector contains the specified element.       * Returns {@code true} if this vector contains the specified element.
377       * More formally, returns {@code true} if and only if this vector       * More formally, returns {@code true} if and only if this vector
378       * contains at least one element {@code e} such that       * contains at least one element {@code e} such that
379       * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.       * {@code Objects.equals(o, e)}.
380       *       *
381       * @param o element whose presence in this vector is to be tested       * @param o element whose presence in this vector is to be tested
382       * @return {@code true} if this vector contains the specified element       * @return {@code true} if this vector contains the specified element
# Line 344  Line 389 
389       * Returns the index of the first occurrence of the specified element       * 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.       * in this vector, or -1 if this vector does not contain the element.
391       * More formally, returns the lowest index {@code i} such that       * 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>,       * {@code Objects.equals(o, get(i))},
393       * or -1 if there is no such index.       * or -1 if there is no such index.
394       *       *
395       * @param o element to search for       * @param o element to search for
# Line 360  Line 405 
405       * this vector, searching forwards from {@code index}, or returns -1 if       * this vector, searching forwards from {@code index}, or returns -1 if
406       * the element is not found.       * the element is not found.
407       * More formally, returns the lowest index {@code i} such that       * 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>,       * {@code (i >= index && Objects.equals(o, get(i)))},
409       * or -1 if there is no such index.       * or -1 if there is no such index.
410       *       *
411       * @param o element to search for       * @param o element to search for
# Line 388  Line 433 
433       * Returns the index of the last occurrence of the specified element       * 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.       * in this vector, or -1 if this vector does not contain the element.
435       * More formally, returns the highest index {@code i} such that       * 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>,       * {@code Objects.equals(o, get(i))},
437       * or -1 if there is no such index.       * or -1 if there is no such index.
438       *       *
439       * @param o element to search for       * @param o element to search for
# Line 404  Line 449 
449       * this vector, searching backwards from {@code index}, or returns -1 if       * this vector, searching backwards from {@code index}, or returns -1 if
450       * the element is not found.       * the element is not found.
451       * More formally, returns the highest index {@code i} such that       * 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>,       * {@code (i <= index && Objects.equals(o, get(i)))},
453       * or -1 if there is no such index.       * or -1 if there is no such index.
454       *       *
455       * @param o element to search for       * @param o element to search for
# Line 526  Line 571 
571       *         ({@code index < 0 || index >= size()})       *         ({@code index < 0 || index >= size()})
572       */       */
573      public synchronized void removeElementAt(int index) {      public synchronized void removeElementAt(int index) {
         modCount++;  
574          if (index >= elementCount) {          if (index >= elementCount) {
575              throw new ArrayIndexOutOfBoundsException(index + " >= " +              throw new ArrayIndexOutOfBoundsException(index + " >= " +
576                                                       elementCount);                                                       elementCount);
# Line 538  Line 582 
582          if (j > 0) {          if (j > 0) {
583              System.arraycopy(elementData, index + 1, elementData, index, j);              System.arraycopy(elementData, index + 1, elementData, index, j);
584          }          }
585            modCount++;
586          elementCount--;          elementCount--;
587          elementData[elementCount] = null; /* to let gc do its work */          elementData[elementCount] = null; /* to let gc do its work */
588      }      }
# Line 566  Line 611 
611       *         ({@code index < 0 || index > size()})       *         ({@code index < 0 || index > size()})
612       */       */
613      public synchronized void insertElementAt(E obj, int index) {      public synchronized void insertElementAt(E obj, int index) {
         modCount++;  
614          if (index > elementCount) {          if (index > elementCount) {
615              throw new ArrayIndexOutOfBoundsException(index              throw new ArrayIndexOutOfBoundsException(index
616                                                       + " > " + elementCount);                                                       + " > " + elementCount);
617          }          }
618          ensureCapacityHelper(elementCount + 1);          modCount++;
619          System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);          final int s = elementCount;
620            Object[] elementData = this.elementData;
621            if (s == elementData.length)
622                elementData = grow();
623            System.arraycopy(elementData, index,
624                             elementData, index + 1,
625                             s - index);
626          elementData[index] = obj;          elementData[index] = obj;
627          elementCount++;          elementCount = s + 1;
628      }      }
629    
630      /**      /**
# Line 590  Line 640 
640       */       */
641      public synchronized void addElement(E obj) {      public synchronized void addElement(E obj) {
642          modCount++;          modCount++;
643          ensureCapacityHelper(elementCount + 1);          add(obj, elementData, elementCount);
         elementData[elementCount++] = obj;  
644      }      }
645    
646      /**      /**
# Line 626  Line 675 
675       * method (which is part of the {@link List} interface).       * method (which is part of the {@link List} interface).
676       */       */
677      public synchronized void removeAllElements() {      public synchronized void removeAllElements() {
         modCount++;  
678          // Let gc do its work          // Let gc do its work
679          for (int i = 0; i < elementCount; i++)          for (int i = 0; i < elementCount; i++)
680              elementData[i] = null;              elementData[i] = null;
681    
682            modCount++;
683          elementCount = 0;          elementCount = 0;
684      }      }
685    
# Line 650  Line 699 
699              return v;              return v;
700          } catch (CloneNotSupportedException e) {          } catch (CloneNotSupportedException e) {
701              // this shouldn't happen, since we are Cloneable              // this shouldn't happen, since we are Cloneable
702              throw new InternalError();              throw new InternalError(e);
703          }          }
704      }      }
705    
# Line 678  Line 727 
727       * of the Vector <em>only</em> if the caller knows that the Vector       * of the Vector <em>only</em> if the caller knows that the Vector
728       * does not contain any null elements.)       * 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       * @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       *          be stored, if it is big enough; otherwise, a new array of the
734       *          same runtime type is allocated for this purpose.       *          same runtime type is allocated for this purpose.
735       * @return an array containing the elements of the Vector       * @return an array containing the elements of the Vector
736       * @throws ArrayStoreException if the runtime type of a is not a supertype       * @throws ArrayStoreException if the runtime type of a, {@code <T>}, is not
737       * of the runtime type of every element in this Vector       * a supertype of the runtime type, {@code <E>}, of every element in this
738         * Vector
739       * @throws NullPointerException if the given array is null       * @throws NullPointerException if the given array is null
740       * @since 1.2       * @since 1.2
741       */       */
# Line 744  Line 796 
796      }      }
797    
798      /**      /**
799         * This helper method split out from add(E) to keep method
800         * bytecode size under 35 (the -XX:MaxInlineSize default value),
801         * which helps when add(E) is called in a C1-compiled loop.
802         */
803        private void add(E e, Object[] elementData, int s) {
804            if (s == elementData.length)
805                elementData = grow();
806            elementData[s] = e;
807            elementCount = s + 1;
808        }
809    
810        /**
811       * Appends the specified element to the end of this Vector.       * Appends the specified element to the end of this Vector.
812       *       *
813       * @param e element to be appended to this Vector       * @param e element to be appended to this Vector
# Line 752  Line 816 
816       */       */
817      public synchronized boolean add(E e) {      public synchronized boolean add(E e) {
818          modCount++;          modCount++;
819          ensureCapacityHelper(elementCount + 1);          add(e, elementData, elementCount);
         elementData[elementCount++] = e;  
820          return true;          return true;
821      }      }
822    
# Line 761  Line 824 
824       * Removes the first occurrence of the specified element in this Vector       * Removes the first occurrence of the specified element in this Vector
825       * If the Vector does not contain the element, it is unchanged.  More       * If the Vector does not contain the element, it is unchanged.  More
826       * formally, removes the element with the lowest index i such that       * formally, removes the element with the lowest index i such that
827       * {@code (o==null ? get(i)==null : o.equals(get(i)))} (if such       * {@code Objects.equals(o, get(i))} (if such
828       * an element exists).       * an element exists).
829       *       *
830       * @param o element to be removed from this Vector, if present       * @param o element to be removed from this Vector, if present
# Line 852  Line 915 
915       * @throws NullPointerException if the specified collection is null       * @throws NullPointerException if the specified collection is null
916       * @since 1.2       * @since 1.2
917       */       */
918      public synchronized boolean addAll(Collection<? extends E> c) {      public boolean addAll(Collection<? extends E> c) {
         modCount++;  
919          Object[] a = c.toArray();          Object[] a = c.toArray();
920            modCount++;
921          int numNew = a.length;          int numNew = a.length;
922          ensureCapacityHelper(elementCount + numNew);          if (numNew == 0)
923          System.arraycopy(a, 0, elementData, elementCount, numNew);              return false;
924          elementCount += numNew;          synchronized (this) {
925          return numNew != 0;              Object[] elementData = this.elementData;
926                final int s = elementCount;
927                if (numNew > elementData.length - s)
928                    elementData = grow(s + numNew);
929                System.arraycopy(a, 0, elementData, s, numNew);
930                elementCount = s + numNew;
931                return true;
932            }
933      }      }
934    
935      /**      /**
# Line 870  Line 940 
940       * @return true if this Vector changed as a result of the call       * @return true if this Vector changed as a result of the call
941       * @throws ClassCastException if the types of one or more elements       * @throws ClassCastException if the types of one or more elements
942       *         in this vector are incompatible with the specified       *         in this vector are incompatible with the specified
943       *         collection (optional)       *         collection
944         * (<a href="Collection.html#optional-restrictions">optional</a>)
945       * @throws NullPointerException if this vector contains one or more null       * @throws NullPointerException if this vector contains one or more null
946       *         elements and the specified collection does not support null       *         elements and the specified collection does not support null
947       *         elements (optional), or if the specified collection is null       *         elements
948         * (<a href="Collection.html#optional-restrictions">optional</a>),
949         *         or if the specified collection is null
950       * @since 1.2       * @since 1.2
951       */       */
952      public synchronized boolean removeAll(Collection<?> c) {      public synchronized boolean removeAll(Collection<?> c) {
# Line 890  Line 963 
963       * @return true if this Vector changed as a result of the call       * @return true if this Vector changed as a result of the call
964       * @throws ClassCastException if the types of one or more elements       * @throws ClassCastException if the types of one or more elements
965       *         in this vector are incompatible with the specified       *         in this vector are incompatible with the specified
966       *         collection (optional)       *         collection
967         * (<a href="Collection.html#optional-restrictions">optional</a>)
968       * @throws NullPointerException if this vector contains one or more null       * @throws NullPointerException if this vector contains one or more null
969       *         elements and the specified collection does not support null       *         elements and the specified collection does not support null
970       *         elements (optional), or if the specified collection is null       *         elements
971         *         (<a href="Collection.html#optional-restrictions">optional</a>),
972         *         or if the specified collection is null
973       * @since 1.2       * @since 1.2
974       */       */
975      public synchronized boolean retainAll(Collection<?> c) {      public synchronized boolean retainAll(Collection<?> c) {
# Line 918  Line 994 
994       * @since 1.2       * @since 1.2
995       */       */
996      public synchronized boolean addAll(int index, Collection<? extends E> c) {      public synchronized boolean addAll(int index, Collection<? extends E> c) {
         modCount++;  
997          if (index < 0 || index > elementCount)          if (index < 0 || index > elementCount)
998              throw new ArrayIndexOutOfBoundsException(index);              throw new ArrayIndexOutOfBoundsException(index);
999    
1000          Object[] a = c.toArray();          Object[] a = c.toArray();
1001            modCount++;
1002          int numNew = a.length;          int numNew = a.length;
1003          ensureCapacityHelper(elementCount + numNew);          if (numNew == 0)
1004                return false;
1005            Object[] elementData = this.elementData;
1006            final int s = elementCount;
1007            if (numNew > elementData.length - s)
1008                elementData = grow(s + numNew);
1009    
1010          int numMoved = elementCount - index;          int numMoved = s - index;
1011          if (numMoved > 0)          if (numMoved > 0)
1012              System.arraycopy(elementData, index, elementData, index + numNew,              System.arraycopy(elementData, index,
1013                                 elementData, index + numNew,
1014                               numMoved);                               numMoved);
   
1015          System.arraycopy(a, 0, elementData, index, numNew);          System.arraycopy(a, 0, elementData, index, numNew);
1016          elementCount += numNew;          elementCount = s + numNew;
1017          return numNew != 0;          return true;
1018      }      }
1019    
1020      /**      /**
# Line 941  Line 1022 
1022       * true if and only if the specified Object is also a List, both Lists       * true if and only if the specified Object is also a List, both Lists
1023       * have the same size, and all corresponding pairs of elements in the two       * have the same size, and all corresponding pairs of elements in the two
1024       * Lists are <em>equal</em>.  (Two elements {@code e1} and       * Lists are <em>equal</em>.  (Two elements {@code e1} and
1025       * {@code e2} are <em>equal</em> if {@code (e1==null ? e2==null :       * {@code e2} are <em>equal</em> if {@code Objects.equals(e1, e2)}.)
1026       * e1.equals(e2))}.)  In other words, two Lists are defined to be       * In other words, two Lists are defined to be
1027       * equal if they contain the same elements in the same order.       * equal if they contain the same elements in the same order.
1028       *       *
1029       * @param o the Object to be compared for equality with this Vector       * @param o the Object to be compared for equality with this Vector
# Line 1014  Line 1095 
1095       * (If {@code toIndex==fromIndex}, this operation has no effect.)       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1096       */       */
1097      protected synchronized void removeRange(int fromIndex, int toIndex) {      protected synchronized void removeRange(int fromIndex, int toIndex) {
         modCount++;  
1098          int numMoved = elementCount - toIndex;          int numMoved = elementCount - toIndex;
1099          System.arraycopy(elementData, toIndex, elementData, fromIndex,          System.arraycopy(elementData, toIndex, elementData, fromIndex,
1100                           numMoved);                           numMoved);
1101    
1102          // Let gc do its work          // Let gc do its work
1103            modCount++;
1104          int newElementCount = elementCount - (toIndex-fromIndex);          int newElementCount = elementCount - (toIndex-fromIndex);
1105          while (elementCount != newElementCount)          while (elementCount != newElementCount)
1106              elementData[--elementCount] = null;              elementData[--elementCount] = null;
# Line 1027  Line 1108 
1108    
1109      /**      /**
1110       * Save the state of the {@code Vector} instance to a stream (that       * Save the state of the {@code Vector} instance to a stream (that
1111       * is, serialize it).  This method is present merely for synchronization.       * is, serialize it).
1112       * It just calls the default writeObject method.       * This method performs synchronization to ensure the consistency
1113       */       * of the serialized data.
1114      private synchronized void writeObject(java.io.ObjectOutputStream s)       */
1115          throws java.io.IOException      private void writeObject(java.io.ObjectOutputStream s)
1116      {              throws java.io.IOException {
1117          s.defaultWriteObject();          final java.io.ObjectOutputStream.PutField fields = s.putFields();
1118            final Object[] data;
1119            synchronized (this) {
1120                fields.put("capacityIncrement", capacityIncrement);
1121                fields.put("elementCount", elementCount);
1122                data = elementData.clone();
1123            }
1124            fields.put("elementData", data);
1125            s.writeFields();
1126      }      }
1127    
1128      /**      /**
# Line 1114  Line 1203 
1203              lastRet = -1;              lastRet = -1;
1204          }          }
1205    
1206            @Override
1207            public void forEachRemaining(Consumer<? super E> action) {
1208                Objects.requireNonNull(action);
1209                synchronized (Vector.this) {
1210                    final int size = elementCount;
1211                    int i = cursor;
1212                    if (i >= size) {
1213                        return;
1214                    }
1215            @SuppressWarnings("unchecked")
1216                    final E[] elementData = (E[]) Vector.this.elementData;
1217                    if (i >= elementData.length) {
1218                        throw new ConcurrentModificationException();
1219                    }
1220                    while (i != size && modCount == expectedModCount) {
1221                        action.accept(elementData[i++]);
1222                    }
1223                    // update once at end of iteration to reduce heap write traffic
1224                    cursor = i;
1225                    lastRet = i - 1;
1226                    checkForComodification();
1227                }
1228            }
1229    
1230          final void checkForComodification() {          final void checkForComodification() {
1231              if (modCount != expectedModCount)              if (modCount != expectedModCount)
1232                  throw new ConcurrentModificationException();                  throw new ConcurrentModificationException();
# Line 1172  Line 1285 
1285              lastRet = -1;              lastRet = -1;
1286          }          }
1287      }      }
1288    
1289        @Override
1290        public synchronized void forEach(Consumer<? super E> action) {
1291            Objects.requireNonNull(action);
1292            final int expectedModCount = modCount;
1293            @SuppressWarnings("unchecked")
1294            final E[] elementData = (E[]) this.elementData;
1295            final int elementCount = this.elementCount;
1296            for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
1297                action.accept(elementData[i]);
1298            }
1299            if (modCount != expectedModCount) {
1300                throw new ConcurrentModificationException();
1301            }
1302        }
1303    
1304        @Override
1305        @SuppressWarnings("unchecked")
1306        public synchronized boolean removeIf(Predicate<? super E> filter) {
1307            Objects.requireNonNull(filter);
1308            // figure out which elements are to be removed
1309            // any exception thrown from the filter predicate at this stage
1310            // will leave the collection unmodified
1311            int removeCount = 0;
1312            final int size = elementCount;
1313            final BitSet removeSet = new BitSet(size);
1314            final int expectedModCount = modCount;
1315            for (int i=0; modCount == expectedModCount && i < size; i++) {
1316                @SuppressWarnings("unchecked")
1317                final E element = (E) elementData[i];
1318                if (filter.test(element)) {
1319                    removeSet.set(i);
1320                    removeCount++;
1321                }
1322            }
1323            if (modCount != expectedModCount) {
1324                throw new ConcurrentModificationException();
1325            }
1326    
1327            // shift surviving elements left over the spaces left by removed elements
1328            final boolean anyToRemove = removeCount > 0;
1329            if (anyToRemove) {
1330                final int newSize = size - removeCount;
1331                for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1332                    i = removeSet.nextClearBit(i);
1333                    elementData[j] = elementData[i];
1334                }
1335                for (int k=newSize; k < size; k++) {
1336                    elementData[k] = null;  // Let gc do its work
1337                }
1338                elementCount = newSize;
1339                if (modCount != expectedModCount) {
1340                    throw new ConcurrentModificationException();
1341                }
1342                modCount++;
1343            }
1344    
1345            return anyToRemove;
1346        }
1347    
1348        @Override
1349        @SuppressWarnings("unchecked")
1350        public synchronized void replaceAll(UnaryOperator<E> operator) {
1351            Objects.requireNonNull(operator);
1352            final int expectedModCount = modCount;
1353            final int size = elementCount;
1354            for (int i=0; modCount == expectedModCount && i < size; i++) {
1355                elementData[i] = operator.apply((E) elementData[i]);
1356            }
1357            if (modCount != expectedModCount) {
1358                throw new ConcurrentModificationException();
1359            }
1360            modCount++;
1361        }
1362    
1363        @SuppressWarnings("unchecked")
1364        @Override
1365        public synchronized void sort(Comparator<? super E> c) {
1366            final int expectedModCount = modCount;
1367            Arrays.sort((E[]) elementData, 0, elementCount, c);
1368            if (modCount != expectedModCount) {
1369                throw new ConcurrentModificationException();
1370            }
1371            modCount++;
1372        }
1373    
1374        /**
1375         * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1376         * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1377         * list.
1378         *
1379         * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1380         * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1381         * Overriding implementations should document the reporting of additional
1382         * characteristic values.
1383         *
1384         * @return a {@code Spliterator} over the elements in this list
1385         * @since 1.8
1386         */
1387        @Override
1388        public Spliterator<E> spliterator() {
1389            return new VectorSpliterator<>(this, null, 0, -1, 0);
1390        }
1391    
1392        /** Similar to ArrayList Spliterator */
1393        static final class VectorSpliterator<E> implements Spliterator<E> {
1394            private final Vector<E> list;
1395            private Object[] array;
1396            private int index; // current index, modified on advance/split
1397            private int fence; // -1 until used; then one past last index
1398            private int expectedModCount; // initialized when fence set
1399    
1400            /** Create new spliterator covering the given  range */
1401            VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1402                              int expectedModCount) {
1403                this.list = list;
1404                this.array = array;
1405                this.index = origin;
1406                this.fence = fence;
1407                this.expectedModCount = expectedModCount;
1408            }
1409    
1410            private int getFence() { // initialize on first use
1411                int hi;
1412                if ((hi = fence) < 0) {
1413                    synchronized(list) {
1414                        array = list.elementData;
1415                        expectedModCount = list.modCount;
1416                        hi = fence = list.elementCount;
1417                    }
1418                }
1419                return hi;
1420            }
1421    
1422            public Spliterator<E> trySplit() {
1423                int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1424                return (lo >= mid) ? null :
1425                    new VectorSpliterator<>(list, array, lo, index = mid,
1426                                            expectedModCount);
1427            }
1428    
1429            @SuppressWarnings("unchecked")
1430            public boolean tryAdvance(Consumer<? super E> action) {
1431                int i;
1432                if (action == null)
1433                    throw new NullPointerException();
1434                if (getFence() > (i = index)) {
1435                    index = i + 1;
1436                    action.accept((E)array[i]);
1437                    if (list.modCount != expectedModCount)
1438                        throw new ConcurrentModificationException();
1439                    return true;
1440                }
1441                return false;
1442            }
1443    
1444            @SuppressWarnings("unchecked")
1445            public void forEachRemaining(Consumer<? super E> action) {
1446                int i, hi; // hoist accesses and checks from loop
1447                Vector<E> lst; Object[] a;
1448                if (action == null)
1449                    throw new NullPointerException();
1450                if ((lst = list) != null) {
1451                    if ((hi = fence) < 0) {
1452                        synchronized(lst) {
1453                            expectedModCount = lst.modCount;
1454                            a = array = lst.elementData;
1455                            hi = fence = lst.elementCount;
1456                        }
1457                    }
1458                    else
1459                        a = array;
1460                    if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1461                        while (i < hi)
1462                            action.accept((E) a[i++]);
1463                        if (lst.modCount == expectedModCount)
1464                            return;
1465                    }
1466                }
1467                throw new ConcurrentModificationException();
1468            }
1469    
1470            public long estimateSize() {
1471                return getFence() - index;
1472            }
1473    
1474            public int characteristics() {
1475                return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1476            }
1477        }
1478  }  }

Legend:
Removed from v.1.29  
changed lines
  Added in v.1.30

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8