ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
(Generate patch)

Comparing jsr166/src/main/java/util/ArrayList.java (file contents):
Revision 1.33 by jsr166, Mon Oct 17 21:46:27 2016 UTC vs.
Revision 1.46 by jsr166, Fri Dec 2 06:41:08 2016 UTC

# Line 104 | Line 104 | import java.util.function.UnaryOperator;
104   * @see     Vector
105   * @since   1.2
106   */
107
107   public class ArrayList<E> extends AbstractList<E>
108          implements List<E>, RandomAccess, Cloneable, java.io.Serializable
109   {
# Line 424 | Line 423 | public class ArrayList<E> extends Abstra
423          return (E) elementData[index];
424      }
425  
426 +    @SuppressWarnings("unchecked")
427 +    static <E> E elementAt(Object[] es, int index) {
428 +        return (E) es[index];
429 +    }
430 +
431      /**
432       * Returns the element at the specified position in this list.
433       *
# Line 497 | Line 501 | public class ArrayList<E> extends Abstra
501                           s - index);
502          elementData[index] = element;
503          size = s + 1;
504 +        // checkInvariants();
505      }
506  
507      /**
# Line 520 | Line 525 | public class ArrayList<E> extends Abstra
525                               numMoved);
526          elementData[--size] = null; // clear to let GC do its work
527  
528 +        // checkInvariants();
529          return oldValue;
530      }
531  
# Line 553 | Line 559 | public class ArrayList<E> extends Abstra
559          return false;
560      }
561  
562 <    /*
562 >    /**
563       * Private remove method that skips bounds checking and does not
564       * return the value removed.
565       */
# Line 572 | Line 578 | public class ArrayList<E> extends Abstra
578       */
579      public void clear() {
580          modCount++;
581 <
576 <        // clear to let GC do its work
577 <        for (int i = 0; i < size; i++)
578 <            elementData[i] = null;
579 <
581 >        Arrays.fill(elementData, 0, size, null);
582          size = 0;
583      }
584  
# Line 605 | Line 607 | public class ArrayList<E> extends Abstra
607              elementData = grow(s + numNew);
608          System.arraycopy(a, 0, elementData, s, numNew);
609          size = s + numNew;
610 +        // checkInvariants();
611          return true;
612      }
613  
# Line 643 | Line 646 | public class ArrayList<E> extends Abstra
646                               numMoved);
647          System.arraycopy(a, 0, elementData, index, numNew);
648          size = s + numNew;
649 +        // checkInvariants();
650          return true;
651      }
652  
# Line 665 | Line 669 | public class ArrayList<E> extends Abstra
669                      outOfBoundsMsg(fromIndex, toIndex));
670          }
671          modCount++;
672 <        int numMoved = size - toIndex;
673 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
674 <                         numMoved);
675 <
676 <        // clear to let GC do its work
673 <        int newSize = size - (toIndex-fromIndex);
674 <        for (int i = newSize; i < size; i++) {
675 <            elementData[i] = null;
676 <        }
677 <        size = newSize;
672 >        final Object[] es = elementData;
673 >        final int oldSize = size;
674 >        System.arraycopy(es, toIndex, es, fromIndex, oldSize - toIndex);
675 >        Arrays.fill(es, size -= (toIndex - fromIndex), oldSize, null);
676 >        // checkInvariants();
677      }
678  
679      /**
# Line 717 | Line 716 | public class ArrayList<E> extends Abstra
716       * @see Collection#contains(Object)
717       */
718      public boolean removeAll(Collection<?> c) {
719 <        Objects.requireNonNull(c);
721 <        return batchRemove(c, false);
719 >        return batchRemove(c, false, 0, size);
720      }
721  
722      /**
# Line 738 | Line 736 | public class ArrayList<E> extends Abstra
736       * @see Collection#contains(Object)
737       */
738      public boolean retainAll(Collection<?> c) {
739 <        Objects.requireNonNull(c);
742 <        return batchRemove(c, true);
739 >        return batchRemove(c, true, 0, size);
740      }
741  
742 <    private boolean batchRemove(Collection<?> c, boolean complement) {
743 <        final Object[] elementData = this.elementData;
744 <        int r = 0, w = 0;
745 <        boolean modified = false;
746 <        try {
747 <            for (; r < size; r++)
748 <                if (c.contains(elementData[r]) == complement)
749 <                    elementData[w++] = elementData[r];
750 <        } finally {
751 <            // Preserve behavioral compatibility with AbstractCollection,
752 <            // even if c.contains() throws.
753 <            if (r != size) {
754 <                System.arraycopy(elementData, r,
755 <                                 elementData, w,
756 <                                 size - r);
757 <                w += size - r;
758 <            }
759 <            if (w != size) {
760 <                // clear to let GC do its work
761 <                for (int i = w; i < size; i++)
762 <                    elementData[i] = null;
763 <                modCount += size - w;
764 <                size = w;
765 <                modified = true;
742 >    boolean batchRemove(Collection<?> c, boolean complement,
743 >                        final int from, final int end) {
744 >        Objects.requireNonNull(c);
745 >        final Object[] es = elementData;
746 >        final boolean modified;
747 >        int r;
748 >        // Optimize for initial run of survivors
749 >        for (r = from; r < end && c.contains(es[r]) == complement; r++)
750 >            ;
751 >        if (modified = (r < end)) {
752 >            int w = r++;
753 >            try {
754 >                for (Object e; r < end; r++)
755 >                    if (c.contains(e = es[r]) == complement)
756 >                        es[w++] = e;
757 >            } catch (Throwable ex) {
758 >                // Preserve behavioral compatibility with AbstractCollection,
759 >                // even if c.contains() throws.
760 >                System.arraycopy(es, r, es, w, end - r);
761 >                w += end - r;
762 >                throw ex;
763 >            } finally {
764 >                final int oldSize = size, deleted = end - w;
765 >                modCount += deleted;
766 >                System.arraycopy(es, end, es, w, oldSize - end);
767 >                Arrays.fill(es, size -= deleted, oldSize, null);
768              }
769          }
770 +        // checkInvariants();
771          return modified;
772      }
773  
774      /**
775 <     * Save the state of the {@code ArrayList} instance to a stream (that
776 <     * is, serialize it).
775 >     * Saves the state of the {@code ArrayList} instance to a stream
776 >     * (that is, serializes it).
777       *
778 +     * @param s the stream
779 +     * @throws java.io.IOException if an I/O error occurs
780       * @serialData The length of the array backing the {@code ArrayList}
781       *             instance is emitted (int), followed by all of its elements
782       *             (each an {@code Object}) in the proper order.
783       */
784      private void writeObject(java.io.ObjectOutputStream s)
785 <        throws java.io.IOException{
785 >        throws java.io.IOException {
786          // Write out element count, and any hidden stuff
787          int expectedModCount = modCount;
788          s.defaultWriteObject();
# Line 799 | Line 801 | public class ArrayList<E> extends Abstra
801      }
802  
803      /**
804 <     * Reconstitute the {@code ArrayList} instance from a stream (that is,
805 <     * deserialize it).
804 >     * Reconstitutes the {@code ArrayList} instance from a stream (that is,
805 >     * deserializes it).
806 >     * @param s the stream
807 >     * @throws ClassNotFoundException if the class of a serialized object
808 >     *         could not be found
809 >     * @throws java.io.IOException if an I/O error occurs
810       */
811      private void readObject(java.io.ObjectInputStream s)
812          throws java.io.IOException, ClassNotFoundException {
# Line 912 | Line 918 | public class ArrayList<E> extends Abstra
918          }
919  
920          @Override
921 <        @SuppressWarnings("unchecked")
922 <        public void forEachRemaining(Consumer<? super E> consumer) {
917 <            Objects.requireNonNull(consumer);
921 >        public void forEachRemaining(Consumer<? super E> action) {
922 >            Objects.requireNonNull(action);
923              final int size = ArrayList.this.size;
924              int i = cursor;
925 <            if (i >= size) {
926 <                return;
927 <            }
928 <            final Object[] elementData = ArrayList.this.elementData;
929 <            if (i >= elementData.length) {
930 <                throw new ConcurrentModificationException();
931 <            }
932 <            while (i != size && modCount == expectedModCount) {
933 <                consumer.accept((E) elementData[i++]);
925 >            if (i < size) {
926 >                final Object[] es = elementData;
927 >                if (i >= es.length)
928 >                    throw new ConcurrentModificationException();
929 >                for (; i < size && modCount == expectedModCount; i++)
930 >                    action.accept(elementAt(es, i));
931 >                // update once at end to reduce heap write traffic
932 >                cursor = i;
933 >                lastRet = i - 1;
934 >                checkForComodification();
935              }
930            // update once at end of iteration to reduce heap write traffic
931            cursor = i;
932            lastRet = i - 1;
933            checkForComodification();
936          }
937  
938          final void checkForComodification() {
# Line 1117 | Line 1119 | public class ArrayList<E> extends Abstra
1119              return true;
1120          }
1121  
1122 +        public boolean removeAll(Collection<?> c) {
1123 +            return batchRemove(c, false);
1124 +        }
1125 +
1126 +        public boolean retainAll(Collection<?> c) {
1127 +            return batchRemove(c, true);
1128 +        }
1129 +
1130 +        private boolean batchRemove(Collection<?> c, boolean complement) {
1131 +            checkForComodification();
1132 +            int oldSize = root.size;
1133 +            boolean modified =
1134 +                root.batchRemove(c, complement, offset, offset + size);
1135 +            if (modified)
1136 +                updateSizeAndModCount(root.size - oldSize);
1137 +            return modified;
1138 +        }
1139 +
1140 +        public boolean removeIf(Predicate<? super E> filter) {
1141 +            checkForComodification();
1142 +            int oldSize = root.size;
1143 +            boolean modified = root.removeIf(filter, offset, offset + size);
1144 +            if (modified)
1145 +                updateSizeAndModCount(root.size - oldSize);
1146 +            return modified;
1147 +        }
1148 +
1149          public Iterator<E> iterator() {
1150              return listIterator();
1151          }
# Line 1164 | Line 1193 | public class ArrayList<E> extends Abstra
1193                      return (E) elementData[offset + (lastRet = i)];
1194                  }
1195  
1196 <                @SuppressWarnings("unchecked")
1197 <                public void forEachRemaining(Consumer<? super E> consumer) {
1169 <                    Objects.requireNonNull(consumer);
1196 >                public void forEachRemaining(Consumer<? super E> action) {
1197 >                    Objects.requireNonNull(action);
1198                      final int size = SubList.this.size;
1199                      int i = cursor;
1200 <                    if (i >= size) {
1201 <                        return;
1202 <                    }
1203 <                    final Object[] elementData = root.elementData;
1204 <                    if (offset + i >= elementData.length) {
1205 <                        throw new ConcurrentModificationException();
1206 <                    }
1207 <                    while (i != size && modCount == expectedModCount) {
1208 <                        consumer.accept((E) elementData[offset + (i++)]);
1200 >                    if (i < size) {
1201 >                        final Object[] es = root.elementData;
1202 >                        if (offset + i >= es.length)
1203 >                            throw new ConcurrentModificationException();
1204 >                        for (; i < size && modCount == expectedModCount; i++)
1205 >                            action.accept(elementAt(es, offset + i));
1206 >                        // update once at end to reduce heap write traffic
1207 >                        cursor = i;
1208 >                        lastRet = i - 1;
1209 >                        checkForComodification();
1210                      }
1182                    // update once at end of iteration to reduce heap write traffic
1183                    lastRet = cursor = i;
1184                    checkForComodification();
1211                  }
1212  
1213                  public int nextIndex() {
# Line 1271 | Line 1297 | public class ArrayList<E> extends Abstra
1297          public Spliterator<E> spliterator() {
1298              checkForComodification();
1299  
1300 <            // ArrayListSpliterator is not used because late-binding logic
1301 <            // is different here
1276 <            return new Spliterator<>() {
1300 >            // ArrayListSpliterator not used here due to late-binding
1301 >            return new Spliterator<E>() {
1302                  private int index = offset; // current index, modified on advance/split
1303                  private int fence = -1; // -1 until used; then one past last index
1304                  private int expectedModCount; // initialized when fence set
# Line 1287 | Line 1312 | public class ArrayList<E> extends Abstra
1312                      return hi;
1313                  }
1314  
1315 <                public ArrayListSpliterator<E> trySplit() {
1315 >                public ArrayList<E>.ArrayListSpliterator trySplit() {
1316                      int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1317 <                    // ArrayListSpliterator could be used here as the source is already bound
1317 >                    // ArrayListSpliterator can be used here as the source is already bound
1318                      return (lo >= mid) ? null : // divide range in half unless too small
1319 <                        new ArrayListSpliterator<>(root, lo, index = mid,
1295 <                                                   expectedModCount);
1319 >                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1320                  }
1321  
1322                  public boolean tryAdvance(Consumer<? super E> action) {
# Line 1334 | Line 1358 | public class ArrayList<E> extends Abstra
1358                  }
1359  
1360                  public long estimateSize() {
1361 <                    return (long) (getFence() - index);
1361 >                    return getFence() - index;
1362                  }
1363  
1364                  public int characteristics() {
# Line 1348 | Line 1372 | public class ArrayList<E> extends Abstra
1372      public void forEach(Consumer<? super E> action) {
1373          Objects.requireNonNull(action);
1374          final int expectedModCount = modCount;
1375 <        @SuppressWarnings("unchecked")
1352 <        final E[] elementData = (E[]) this.elementData;
1375 >        final Object[] es = elementData;
1376          final int size = this.size;
1377 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1378 <            action.accept(elementData[i]);
1379 <        }
1357 <        if (modCount != expectedModCount) {
1377 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1378 >            action.accept(elementAt(es, i));
1379 >        if (modCount != expectedModCount)
1380              throw new ConcurrentModificationException();
1359        }
1381      }
1382  
1383      /**
# Line 1374 | Line 1395 | public class ArrayList<E> extends Abstra
1395       */
1396      @Override
1397      public Spliterator<E> spliterator() {
1398 <        return new ArrayListSpliterator<>(this, 0, -1, 0);
1398 >        return new ArrayListSpliterator(0, -1, 0);
1399      }
1400  
1401      /** Index-based split-by-two, lazily initialized Spliterator */
1402 <    static final class ArrayListSpliterator<E> implements Spliterator<E> {
1402 >    final class ArrayListSpliterator implements Spliterator<E> {
1403  
1404          /*
1405           * If ArrayLists were immutable, or structurally immutable (no
# Line 1412 | Line 1433 | public class ArrayList<E> extends Abstra
1433           * these streamlinings.
1434           */
1435  
1415        private final ArrayList<E> list;
1436          private int index; // current index, modified on advance/split
1437          private int fence; // -1 until used; then one past last index
1438          private int expectedModCount; // initialized when fence set
1439  
1440 <        /** Create new spliterator covering the given  range */
1441 <        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
1422 <                             int expectedModCount) {
1423 <            this.list = list; // OK if null unless traversed
1440 >        /** Create new spliterator covering the given range */
1441 >        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1442              this.index = origin;
1443              this.fence = fence;
1444              this.expectedModCount = expectedModCount;
# Line 1428 | Line 1446 | public class ArrayList<E> extends Abstra
1446  
1447          private int getFence() { // initialize fence to size on first use
1448              int hi; // (a specialized variant appears in method forEach)
1431            ArrayList<E> lst;
1449              if ((hi = fence) < 0) {
1450 <                if ((lst = list) == null)
1451 <                    hi = fence = 0;
1435 <                else {
1436 <                    expectedModCount = lst.modCount;
1437 <                    hi = fence = lst.size;
1438 <                }
1450 >                expectedModCount = modCount;
1451 >                hi = fence = size;
1452              }
1453              return hi;
1454          }
1455  
1456 <        public ArrayListSpliterator<E> trySplit() {
1456 >        public ArrayListSpliterator trySplit() {
1457              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1458              return (lo >= mid) ? null : // divide range in half unless too small
1459 <                new ArrayListSpliterator<>(list, lo, index = mid,
1447 <                                           expectedModCount);
1459 >                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1460          }
1461  
1462          public boolean tryAdvance(Consumer<? super E> action) {
# Line 1453 | Line 1465 | public class ArrayList<E> extends Abstra
1465              int hi = getFence(), i = index;
1466              if (i < hi) {
1467                  index = i + 1;
1468 <                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
1468 >                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1469                  action.accept(e);
1470 <                if (list.modCount != expectedModCount)
1470 >                if (modCount != expectedModCount)
1471                      throw new ConcurrentModificationException();
1472                  return true;
1473              }
# Line 1464 | Line 1476 | public class ArrayList<E> extends Abstra
1476  
1477          public void forEachRemaining(Consumer<? super E> action) {
1478              int i, hi, mc; // hoist accesses and checks from loop
1479 <            ArrayList<E> lst; Object[] a;
1479 >            Object[] a;
1480              if (action == null)
1481                  throw new NullPointerException();
1482 <            if ((lst = list) != null && (a = lst.elementData) != null) {
1482 >            if ((a = elementData) != null) {
1483                  if ((hi = fence) < 0) {
1484 <                    mc = lst.modCount;
1485 <                    hi = lst.size;
1484 >                    mc = modCount;
1485 >                    hi = size;
1486                  }
1487                  else
1488                      mc = expectedModCount;
# Line 1479 | Line 1491 | public class ArrayList<E> extends Abstra
1491                          @SuppressWarnings("unchecked") E e = (E) a[i];
1492                          action.accept(e);
1493                      }
1494 <                    if (lst.modCount == mc)
1494 >                    if (modCount == mc)
1495                          return;
1496                  }
1497              }
# Line 1487 | Line 1499 | public class ArrayList<E> extends Abstra
1499          }
1500  
1501          public long estimateSize() {
1502 <            return (long) (getFence() - index);
1502 >            return getFence() - index;
1503          }
1504  
1505          public int characteristics() {
# Line 1495 | Line 1507 | public class ArrayList<E> extends Abstra
1507          }
1508      }
1509  
1510 +    // A tiny bit set implementation
1511 +
1512 +    private static long[] nBits(int n) {
1513 +        return new long[((n - 1) >> 6) + 1];
1514 +    }
1515 +    private static void setBit(long[] bits, int i) {
1516 +        bits[i >> 6] |= 1L << i;
1517 +    }
1518 +    private static boolean isClear(long[] bits, int i) {
1519 +        return (bits[i >> 6] & (1L << i)) == 0;
1520 +    }
1521 +
1522      @Override
1523      public boolean removeIf(Predicate<? super E> filter) {
1524 +        return removeIf(filter, 0, size);
1525 +    }
1526 +
1527 +    /**
1528 +     * Removes all elements satisfying the given predicate, from index
1529 +     * i (inclusive) to index end (exclusive).
1530 +     */
1531 +    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1532          Objects.requireNonNull(filter);
1533 <        final int expectedModCount = modCount;
1534 <        final Object[] elementData = this.elementData;
1535 <        int r = 0, w = 0, remaining = size, deleted = 0;
1536 <        try {
1537 <            for (; remaining > 0; remaining--, r++) {
1538 <                @SuppressWarnings("unchecked") E e = (E) elementData[r];
1539 <                if (filter.test(e))
1540 <                    deleted++;
1541 <                else {
1542 <                    if (r != w)
1543 <                        elementData[w] = e;
1544 <                    w++;
1545 <                }
1546 <            }
1533 >        int expectedModCount = modCount;
1534 >        final Object[] es = elementData;
1535 >        // Optimize for initial run of survivors
1536 >        for (; i < end && !filter.test(elementAt(es, i)); i++)
1537 >            ;
1538 >        // Tolerate predicates that reentrantly access the collection for
1539 >        // read (but writers still get CME), so traverse once to find
1540 >        // elements to delete, a second pass to physically expunge.
1541 >        if (i < end) {
1542 >            final int beg = i;
1543 >            final long[] deathRow = nBits(end - beg);
1544 >            deathRow[0] = 1L;   // set bit 0
1545 >            for (i = beg + 1; i < end; i++)
1546 >                if (filter.test(elementAt(es, i)))
1547 >                    setBit(deathRow, i - beg);
1548              if (modCount != expectedModCount)
1549                  throw new ConcurrentModificationException();
1550 <            return deleted > 0;
1551 <        } catch (Throwable ex) {
1552 <            for (; remaining > 0; remaining--, r++, w++)
1553 <                elementData[w] = elementData[r];
1554 <            throw ex;
1555 <        } finally {
1556 <            if (deleted > 0) {
1557 <                modCount++;
1558 <                size -= deleted;
1559 <                while (--deleted >= 0)
1560 <                    elementData[w++] = null;
1561 <            }
1550 >            expectedModCount++;
1551 >            modCount++;
1552 >            int w = beg;
1553 >            for (i = beg; i < end; i++)
1554 >                if (isClear(deathRow, i - beg))
1555 >                    es[w++] = es[i];
1556 >            final int oldSize = size;
1557 >            System.arraycopy(es, end, es, w, oldSize - end);
1558 >            Arrays.fill(es, size -= (end - w), oldSize, null);
1559 >            // checkInvariants();
1560 >            return true;
1561 >        } else {
1562 >            if (modCount != expectedModCount)
1563 >                throw new ConcurrentModificationException();
1564 >            // checkInvariants();
1565 >            return false;
1566          }
1567      }
1568  
1569      @Override
1533    @SuppressWarnings("unchecked")
1570      public void replaceAll(UnaryOperator<E> operator) {
1571          Objects.requireNonNull(operator);
1572          final int expectedModCount = modCount;
1573 +        final Object[] es = elementData;
1574          final int size = this.size;
1575 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1576 <            elementData[i] = operator.apply((E) elementData[i]);
1577 <        }
1541 <        if (modCount != expectedModCount) {
1575 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1576 >            es[i] = operator.apply(elementAt(es, i));
1577 >        if (modCount != expectedModCount)
1578              throw new ConcurrentModificationException();
1543        }
1579          modCount++;
1580 +        // checkInvariants();
1581      }
1582  
1583      @Override
# Line 1549 | Line 1585 | public class ArrayList<E> extends Abstra
1585      public void sort(Comparator<? super E> c) {
1586          final int expectedModCount = modCount;
1587          Arrays.sort((E[]) elementData, 0, size, c);
1588 <        if (modCount != expectedModCount) {
1588 >        if (modCount != expectedModCount)
1589              throw new ConcurrentModificationException();
1554        }
1590          modCount++;
1591 +        // checkInvariants();
1592 +    }
1593 +
1594 +    void checkInvariants() {
1595 +        // assert size >= 0;
1596 +        // assert size == elementData.length || elementData[size] == null;
1597      }
1598   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines