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.36 by jsr166, Mon Nov 14 22:46:22 2016 UTC vs.
Revision 1.55 by jsr166, Wed May 22 17:36:58 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved.
2 > * Copyright (c) 1994, 2019, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5   * This code is free software; you can redistribute it and/or modify it
# Line 25 | Line 25
25  
26   package java.util;
27  
28 + import java.io.IOException;
29 + import java.io.ObjectInputStream;
30 + import java.io.StreamCorruptedException;
31   import java.util.function.Consumer;
32   import java.util.function.Predicate;
33   import java.util.function.UnaryOperator;
34  
35 + import jdk.internal.util.ArraysSupport;
36 +
37   /**
38   * The {@code Vector} class implements a growable array of
39   * objects. Like an array, it contains components that can be
# Line 70 | Line 75 | import java.util.function.UnaryOperator;
75   *
76   * <p>As of the Java 2 platform v1.2, this class was retrofitted to
77   * implement the {@link List} interface, making it a member of the
78 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
78 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
79   * Java Collections Framework</a>.  Unlike the new collection
80   * implementations, {@code Vector} is synchronized.  If a thread-safe
81   * implementation is not needed, it is recommended to use {@link
# Line 239 | Line 244 | public class Vector<E>
244      }
245  
246      /**
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    /**
247       * Increases the capacity to ensure that it can hold at least the
248       * number of elements specified by the minimum capacity argument.
249       *
# Line 254 | Line 251 | public class Vector<E>
251       * @throws OutOfMemoryError if minCapacity is less than zero
252       */
253      private Object[] grow(int minCapacity) {
254 <        return elementData = Arrays.copyOf(elementData,
255 <                                           newCapacity(minCapacity));
254 >        int oldCapacity = elementData.length;
255 >        int newCapacity = ArraysSupport.newLength(oldCapacity,
256 >                minCapacity - oldCapacity, /* minimum growth */
257 >                capacityIncrement > 0 ? capacityIncrement : oldCapacity
258 >                                           /* preferred growth */);
259 >        return elementData = Arrays.copyOf(elementData, newCapacity);
260      }
261  
262      private Object[] grow() {
# Line 263 | Line 264 | public class Vector<E>
264      }
265  
266      /**
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    /**
267       * Sets the size of this vector. If the new size is greater than the
268       * current size, new {@code null} items are added to the end of
269       * the vector. If the new size is less than the current size, all
# Line 306 | Line 276 | public class Vector<E>
276          modCount++;
277          if (newSize > elementData.length)
278              grow(newSize);
279 <        for (int i = newSize; i < elementCount; i++)
280 <            elementData[i] = null;
279 >        final Object[] es = elementData;
280 >        for (int to = elementCount, i = newSize; i < to; i++)
281 >            es[i] = null;
282          elementCount = newSize;
283      }
284  
# Line 676 | Line 647 | public class Vector<E>
647       * method (which is part of the {@link List} interface).
648       */
649      public synchronized void removeAllElements() {
650 <        Arrays.fill(elementData, 0, elementCount, null);
650 >        final Object[] es = elementData;
651 >        for (int to = elementCount, i = elementCount = 0; i < to; i++)
652 >            es[i] = null;
653          modCount++;
681        elementCount = 0;
654      }
655  
656      /**
# Line 984 | Line 956 | public class Vector<E>
956          return bulkRemove(e -> !c.contains(e));
957      }
958  
959 +    /**
960 +     * @throws NullPointerException {@inheritDoc}
961 +     */
962      @Override
963      public boolean removeIf(Predicate<? super E> filter) {
964          Objects.requireNonNull(filter);
# Line 1022 | Line 997 | public class Vector<E>
997                      setBit(deathRow, i - beg);
998              if (modCount != expectedModCount)
999                  throw new ConcurrentModificationException();
1025            expectedModCount++;
1000              modCount++;
1001              int w = beg;
1002              for (i = beg; i < end; i++)
1003                  if (isClear(deathRow, i - beg))
1004                      es[w++] = es[i];
1005 <            Arrays.fill(es, elementCount = w, end, null);
1005 >            for (i = elementCount = w; i < end; i++)
1006 >                es[i] = null;
1007              // checkInvariants();
1008              return true;
1009          } else {
# Line 1159 | Line 1134 | public class Vector<E>
1134       * (If {@code toIndex==fromIndex}, this operation has no effect.)
1135       */
1136      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
1137          modCount++;
1138 <        Arrays.fill(es, elementCount -= (toIndex - fromIndex), oldSize, null);
1138 >        shiftTailOverGap(elementData, fromIndex, toIndex);
1139          // checkInvariants();
1140      }
1141  
1142 +    /** Erases the gap from lo to hi, by sliding down following elements. */
1143 +    private void shiftTailOverGap(Object[] es, int lo, int hi) {
1144 +        System.arraycopy(es, hi, es, lo, elementCount - hi);
1145 +        for (int to = elementCount, i = (elementCount -= hi - lo); i < to; i++)
1146 +            es[i] = null;
1147 +    }
1148 +
1149      /**
1150 <     * Save the state of the {@code Vector} instance to a stream (that
1151 <     * is, serialize it).
1150 >     * Loads a {@code Vector} instance from a stream
1151 >     * (that is, deserializes it).
1152 >     * This method performs checks to ensure the consistency
1153 >     * of the fields.
1154 >     *
1155 >     * @param in the stream
1156 >     * @throws java.io.IOException if an I/O error occurs
1157 >     * @throws ClassNotFoundException if the stream contains data
1158 >     *         of a non-existing class
1159 >     */
1160 >    private void readObject(ObjectInputStream in)
1161 >            throws IOException, ClassNotFoundException {
1162 >        ObjectInputStream.GetField gfields = in.readFields();
1163 >        int count = gfields.get("elementCount", 0);
1164 >        Object[] data = (Object[])gfields.get("elementData", null);
1165 >        if (count < 0 || data == null || count > data.length) {
1166 >            throw new StreamCorruptedException("Inconsistent vector internals");
1167 >        }
1168 >        elementCount = count;
1169 >        elementData = data.clone();
1170 >    }
1171 >
1172 >    /**
1173 >     * Saves the state of the {@code Vector} instance to a stream
1174 >     * (that is, serializes it).
1175       * This method performs synchronization to ensure the consistency
1176       * of the serialized data.
1177 +     *
1178 +     * @param s the stream
1179 +     * @throws java.io.IOException if an I/O error occurs
1180       */
1181      private void writeObject(java.io.ObjectOutputStream s)
1182              throws java.io.IOException {
# Line 1345 | Line 1349 | public class Vector<E>
1349          }
1350      }
1351  
1352 +    /**
1353 +     * @throws NullPointerException {@inheritDoc}
1354 +     */
1355      @Override
1356      public synchronized void forEach(Consumer<? super E> action) {
1357          Objects.requireNonNull(action);
# Line 1358 | Line 1365 | public class Vector<E>
1365          // checkInvariants();
1366      }
1367  
1368 +    /**
1369 +     * @throws NullPointerException {@inheritDoc}
1370 +     */
1371      @Override
1372      public synchronized void replaceAll(UnaryOperator<E> operator) {
1373          Objects.requireNonNull(operator);
# Line 1368 | Line 1378 | public class Vector<E>
1378              es[i] = operator.apply(elementAt(es, i));
1379          if (modCount != expectedModCount)
1380              throw new ConcurrentModificationException();
1381 +        // TODO(8203662): remove increment of modCount from ...
1382          modCount++;
1383          // checkInvariants();
1384      }
# Line 1398 | Line 1409 | public class Vector<E>
1409       */
1410      @Override
1411      public Spliterator<E> spliterator() {
1412 <        return new VectorSpliterator<>(this, null, 0, -1, 0);
1412 >        return new VectorSpliterator(null, 0, -1, 0);
1413      }
1414  
1415      /** Similar to ArrayList Spliterator */
1416 <    static final class VectorSpliterator<E> implements Spliterator<E> {
1406 <        private final Vector<E> list;
1416 >    final class VectorSpliterator implements Spliterator<E> {
1417          private Object[] array;
1418          private int index; // current index, modified on advance/split
1419          private int fence; // -1 until used; then one past last index
1420          private int expectedModCount; // initialized when fence set
1421  
1422 <        /** Create new spliterator covering the given range */
1423 <        VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,
1422 >        /** Creates new spliterator covering the given range. */
1423 >        VectorSpliterator(Object[] array, int origin, int fence,
1424                            int expectedModCount) {
1415            this.list = list;
1425              this.array = array;
1426              this.index = origin;
1427              this.fence = fence;
# Line 1422 | Line 1431 | public class Vector<E>
1431          private int getFence() { // initialize on first use
1432              int hi;
1433              if ((hi = fence) < 0) {
1434 <                synchronized (list) {
1435 <                    array = list.elementData;
1436 <                    expectedModCount = list.modCount;
1437 <                    hi = fence = list.elementCount;
1434 >                synchronized (Vector.this) {
1435 >                    array = elementData;
1436 >                    expectedModCount = modCount;
1437 >                    hi = fence = elementCount;
1438                  }
1439              }
1440              return hi;
# Line 1434 | Line 1443 | public class Vector<E>
1443          public Spliterator<E> trySplit() {
1444              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1445              return (lo >= mid) ? null :
1446 <                new VectorSpliterator<>(list, array, lo, index = mid,
1438 <                                        expectedModCount);
1446 >                new VectorSpliterator(array, lo, index = mid, expectedModCount);
1447          }
1448  
1449          @SuppressWarnings("unchecked")
1450          public boolean tryAdvance(Consumer<? super E> action) {
1451 +            Objects.requireNonNull(action);
1452              int i;
1444            if (action == null)
1445                throw new NullPointerException();
1453              if (getFence() > (i = index)) {
1454                  index = i + 1;
1455                  action.accept((E)array[i]);
1456 <                if (list.modCount != expectedModCount)
1456 >                if (modCount != expectedModCount)
1457                      throw new ConcurrentModificationException();
1458                  return true;
1459              }
# Line 1455 | Line 1462 | public class Vector<E>
1462  
1463          @SuppressWarnings("unchecked")
1464          public void forEachRemaining(Consumer<? super E> action) {
1465 <            int i, hi; // hoist accesses and checks from loop
1466 <            Vector<E> lst; Object[] a;
1467 <            if (action == null)
1468 <                throw new NullPointerException();
1469 <            if ((lst = list) != null) {
1470 <                if ((hi = fence) < 0) {
1471 <                    synchronized (lst) {
1472 <                        expectedModCount = lst.modCount;
1466 <                        a = array = lst.elementData;
1467 <                        hi = fence = lst.elementCount;
1468 <                    }
1469 <                }
1470 <                else
1471 <                    a = array;
1472 <                if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {
1473 <                    while (i < hi)
1474 <                        action.accept((E) a[i++]);
1475 <                    if (lst.modCount == expectedModCount)
1476 <                        return;
1477 <                }
1478 <            }
1479 <            throw new ConcurrentModificationException();
1465 >            Objects.requireNonNull(action);
1466 >            final int hi = getFence();
1467 >            final Object[] a = array;
1468 >            int i;
1469 >            for (i = index, index = hi; i < hi; i++)
1470 >                action.accept((E) a[i]);
1471 >            if (modCount != expectedModCount)
1472 >                throw new ConcurrentModificationException();
1473          }
1474  
1475          public long estimateSize() {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines