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.45 by jsr166, Wed Nov 30 03:31:47 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  
# Line 912 | Line 912 | public class ArrayList<E> extends Abstra
912          }
913  
914          @Override
915 <        @SuppressWarnings("unchecked")
916 <        public void forEachRemaining(Consumer<? super E> consumer) {
917 <            Objects.requireNonNull(consumer);
915 >        public void forEachRemaining(Consumer<? super E> action) {
916 >            Objects.requireNonNull(action);
917              final int size = ArrayList.this.size;
918              int i = cursor;
919 <            if (i >= size) {
920 <                return;
921 <            }
922 <            final Object[] elementData = ArrayList.this.elementData;
923 <            if (i >= elementData.length) {
924 <                throw new ConcurrentModificationException();
925 <            }
926 <            while (i != size && modCount == expectedModCount) {
927 <                consumer.accept((E) elementData[i++]);
919 >            if (i < size) {
920 >                final Object[] es = elementData;
921 >                if (i >= es.length)
922 >                    throw new ConcurrentModificationException();
923 >                for (; i < size && modCount == expectedModCount; i++)
924 >                    action.accept(elementAt(es, i));
925 >                // update once at end to reduce heap write traffic
926 >                cursor = i;
927 >                lastRet = i - 1;
928 >                checkForComodification();
929              }
930            // update once at end of iteration to reduce heap write traffic
931            cursor = i;
932            lastRet = i - 1;
933            checkForComodification();
930          }
931  
932          final void checkForComodification() {
# Line 1117 | Line 1113 | public class ArrayList<E> extends Abstra
1113              return true;
1114          }
1115  
1116 +        public boolean removeAll(Collection<?> c) {
1117 +            return batchRemove(c, false);
1118 +        }
1119 +
1120 +        public boolean retainAll(Collection<?> c) {
1121 +            return batchRemove(c, true);
1122 +        }
1123 +
1124 +        private boolean batchRemove(Collection<?> c, boolean complement) {
1125 +            checkForComodification();
1126 +            int oldSize = root.size;
1127 +            boolean modified =
1128 +                root.batchRemove(c, complement, offset, offset + size);
1129 +            if (modified)
1130 +                updateSizeAndModCount(root.size - oldSize);
1131 +            return modified;
1132 +        }
1133 +
1134 +        public boolean removeIf(Predicate<? super E> filter) {
1135 +            checkForComodification();
1136 +            int oldSize = root.size;
1137 +            boolean modified = root.removeIf(filter, offset, offset + size);
1138 +            if (modified)
1139 +                updateSizeAndModCount(root.size - oldSize);
1140 +            return modified;
1141 +        }
1142 +
1143          public Iterator<E> iterator() {
1144              return listIterator();
1145          }
# Line 1164 | Line 1187 | public class ArrayList<E> extends Abstra
1187                      return (E) elementData[offset + (lastRet = i)];
1188                  }
1189  
1190 <                @SuppressWarnings("unchecked")
1191 <                public void forEachRemaining(Consumer<? super E> consumer) {
1169 <                    Objects.requireNonNull(consumer);
1190 >                public void forEachRemaining(Consumer<? super E> action) {
1191 >                    Objects.requireNonNull(action);
1192                      final int size = SubList.this.size;
1193                      int i = cursor;
1194 <                    if (i >= size) {
1195 <                        return;
1196 <                    }
1197 <                    final Object[] elementData = root.elementData;
1198 <                    if (offset + i >= elementData.length) {
1199 <                        throw new ConcurrentModificationException();
1200 <                    }
1201 <                    while (i != size && modCount == expectedModCount) {
1202 <                        consumer.accept((E) elementData[offset + (i++)]);
1194 >                    if (i < size) {
1195 >                        final Object[] es = root.elementData;
1196 >                        if (offset + i >= es.length)
1197 >                            throw new ConcurrentModificationException();
1198 >                        for (; i < size && modCount == expectedModCount; i++)
1199 >                            action.accept(elementAt(es, offset + i));
1200 >                        // update once at end to reduce heap write traffic
1201 >                        cursor = i;
1202 >                        lastRet = i - 1;
1203 >                        checkForComodification();
1204                      }
1182                    // update once at end of iteration to reduce heap write traffic
1183                    lastRet = cursor = i;
1184                    checkForComodification();
1205                  }
1206  
1207                  public int nextIndex() {
# Line 1271 | Line 1291 | public class ArrayList<E> extends Abstra
1291          public Spliterator<E> spliterator() {
1292              checkForComodification();
1293  
1294 <            // ArrayListSpliterator is not used because late-binding logic
1295 <            // is different here
1276 <            return new Spliterator<>() {
1294 >            // ArrayListSpliterator not used here due to late-binding
1295 >            return new Spliterator<E>() {
1296                  private int index = offset; // current index, modified on advance/split
1297                  private int fence = -1; // -1 until used; then one past last index
1298                  private int expectedModCount; // initialized when fence set
# Line 1287 | Line 1306 | public class ArrayList<E> extends Abstra
1306                      return hi;
1307                  }
1308  
1309 <                public ArrayListSpliterator<E> trySplit() {
1309 >                public ArrayList<E>.ArrayListSpliterator trySplit() {
1310                      int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1311 <                    // ArrayListSpliterator could be used here as the source is already bound
1311 >                    // ArrayListSpliterator can be used here as the source is already bound
1312                      return (lo >= mid) ? null : // divide range in half unless too small
1313 <                        new ArrayListSpliterator<>(root, lo, index = mid,
1295 <                                                   expectedModCount);
1313 >                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1314                  }
1315  
1316                  public boolean tryAdvance(Consumer<? super E> action) {
# Line 1334 | Line 1352 | public class ArrayList<E> extends Abstra
1352                  }
1353  
1354                  public long estimateSize() {
1355 <                    return (long) (getFence() - index);
1355 >                    return getFence() - index;
1356                  }
1357  
1358                  public int characteristics() {
# Line 1348 | Line 1366 | public class ArrayList<E> extends Abstra
1366      public void forEach(Consumer<? super E> action) {
1367          Objects.requireNonNull(action);
1368          final int expectedModCount = modCount;
1369 <        @SuppressWarnings("unchecked")
1352 <        final E[] elementData = (E[]) this.elementData;
1369 >        final Object[] es = elementData;
1370          final int size = this.size;
1371 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1372 <            action.accept(elementData[i]);
1373 <        }
1357 <        if (modCount != expectedModCount) {
1371 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1372 >            action.accept(elementAt(es, i));
1373 >        if (modCount != expectedModCount)
1374              throw new ConcurrentModificationException();
1359        }
1375      }
1376  
1377      /**
# Line 1374 | Line 1389 | public class ArrayList<E> extends Abstra
1389       */
1390      @Override
1391      public Spliterator<E> spliterator() {
1392 <        return new ArrayListSpliterator<>(this, 0, -1, 0);
1392 >        return new ArrayListSpliterator(0, -1, 0);
1393      }
1394  
1395      /** Index-based split-by-two, lazily initialized Spliterator */
1396 <    static final class ArrayListSpliterator<E> implements Spliterator<E> {
1396 >    final class ArrayListSpliterator implements Spliterator<E> {
1397  
1398          /*
1399           * If ArrayLists were immutable, or structurally immutable (no
# Line 1412 | Line 1427 | public class ArrayList<E> extends Abstra
1427           * these streamlinings.
1428           */
1429  
1415        private final ArrayList<E> list;
1430          private int index; // current index, modified on advance/split
1431          private int fence; // -1 until used; then one past last index
1432          private int expectedModCount; // initialized when fence set
1433  
1434 <        /** Create new spliterator covering the given  range */
1435 <        ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
1422 <                             int expectedModCount) {
1423 <            this.list = list; // OK if null unless traversed
1434 >        /** Create new spliterator covering the given range */
1435 >        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1436              this.index = origin;
1437              this.fence = fence;
1438              this.expectedModCount = expectedModCount;
# Line 1428 | Line 1440 | public class ArrayList<E> extends Abstra
1440  
1441          private int getFence() { // initialize fence to size on first use
1442              int hi; // (a specialized variant appears in method forEach)
1431            ArrayList<E> lst;
1443              if ((hi = fence) < 0) {
1444 <                if ((lst = list) == null)
1445 <                    hi = fence = 0;
1435 <                else {
1436 <                    expectedModCount = lst.modCount;
1437 <                    hi = fence = lst.size;
1438 <                }
1444 >                expectedModCount = modCount;
1445 >                hi = fence = size;
1446              }
1447              return hi;
1448          }
1449  
1450 <        public ArrayListSpliterator<E> trySplit() {
1450 >        public ArrayListSpliterator trySplit() {
1451              int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1452              return (lo >= mid) ? null : // divide range in half unless too small
1453 <                new ArrayListSpliterator<>(list, lo, index = mid,
1447 <                                           expectedModCount);
1453 >                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1454          }
1455  
1456          public boolean tryAdvance(Consumer<? super E> action) {
# Line 1453 | Line 1459 | public class ArrayList<E> extends Abstra
1459              int hi = getFence(), i = index;
1460              if (i < hi) {
1461                  index = i + 1;
1462 <                @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
1462 >                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1463                  action.accept(e);
1464 <                if (list.modCount != expectedModCount)
1464 >                if (modCount != expectedModCount)
1465                      throw new ConcurrentModificationException();
1466                  return true;
1467              }
# Line 1464 | Line 1470 | public class ArrayList<E> extends Abstra
1470  
1471          public void forEachRemaining(Consumer<? super E> action) {
1472              int i, hi, mc; // hoist accesses and checks from loop
1473 <            ArrayList<E> lst; Object[] a;
1473 >            Object[] a;
1474              if (action == null)
1475                  throw new NullPointerException();
1476 <            if ((lst = list) != null && (a = lst.elementData) != null) {
1476 >            if ((a = elementData) != null) {
1477                  if ((hi = fence) < 0) {
1478 <                    mc = lst.modCount;
1479 <                    hi = lst.size;
1478 >                    mc = modCount;
1479 >                    hi = size;
1480                  }
1481                  else
1482                      mc = expectedModCount;
# Line 1479 | Line 1485 | public class ArrayList<E> extends Abstra
1485                          @SuppressWarnings("unchecked") E e = (E) a[i];
1486                          action.accept(e);
1487                      }
1488 <                    if (lst.modCount == mc)
1488 >                    if (modCount == mc)
1489                          return;
1490                  }
1491              }
# Line 1487 | Line 1493 | public class ArrayList<E> extends Abstra
1493          }
1494  
1495          public long estimateSize() {
1496 <            return (long) (getFence() - index);
1496 >            return getFence() - index;
1497          }
1498  
1499          public int characteristics() {
# Line 1495 | Line 1501 | public class ArrayList<E> extends Abstra
1501          }
1502      }
1503  
1504 +    // A tiny bit set implementation
1505 +
1506 +    private static long[] nBits(int n) {
1507 +        return new long[((n - 1) >> 6) + 1];
1508 +    }
1509 +    private static void setBit(long[] bits, int i) {
1510 +        bits[i >> 6] |= 1L << i;
1511 +    }
1512 +    private static boolean isClear(long[] bits, int i) {
1513 +        return (bits[i >> 6] & (1L << i)) == 0;
1514 +    }
1515 +
1516      @Override
1517      public boolean removeIf(Predicate<? super E> filter) {
1518 +        return removeIf(filter, 0, size);
1519 +    }
1520 +
1521 +    /**
1522 +     * Removes all elements satisfying the given predicate, from index
1523 +     * i (inclusive) to index end (exclusive).
1524 +     */
1525 +    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1526          Objects.requireNonNull(filter);
1527 <        final int expectedModCount = modCount;
1528 <        final Object[] elementData = this.elementData;
1529 <        int r = 0, w = 0, remaining = size, deleted = 0;
1530 <        try {
1531 <            for (; remaining > 0; remaining--, r++) {
1532 <                @SuppressWarnings("unchecked") E e = (E) elementData[r];
1533 <                if (filter.test(e))
1534 <                    deleted++;
1535 <                else {
1536 <                    if (r != w)
1537 <                        elementData[w] = e;
1538 <                    w++;
1539 <                }
1540 <            }
1527 >        int expectedModCount = modCount;
1528 >        final Object[] es = elementData;
1529 >        // Optimize for initial run of survivors
1530 >        for (; i < end && !filter.test(elementAt(es, i)); i++)
1531 >            ;
1532 >        // Tolerate predicates that reentrantly access the collection for
1533 >        // read (but writers still get CME), so traverse once to find
1534 >        // elements to delete, a second pass to physically expunge.
1535 >        if (i < end) {
1536 >            final int beg = i;
1537 >            final long[] deathRow = nBits(end - beg);
1538 >            deathRow[0] = 1L;   // set bit 0
1539 >            for (i = beg + 1; i < end; i++)
1540 >                if (filter.test(elementAt(es, i)))
1541 >                    setBit(deathRow, i - beg);
1542              if (modCount != expectedModCount)
1543                  throw new ConcurrentModificationException();
1544 <            return deleted > 0;
1545 <        } catch (Throwable ex) {
1546 <            for (; remaining > 0; remaining--, r++, w++)
1547 <                elementData[w] = elementData[r];
1548 <            throw ex;
1549 <        } finally {
1550 <            if (deleted > 0) {
1551 <                modCount++;
1552 <                size -= deleted;
1553 <                while (--deleted >= 0)
1554 <                    elementData[w++] = null;
1555 <            }
1544 >            expectedModCount++;
1545 >            modCount++;
1546 >            int w = beg;
1547 >            for (i = beg; i < end; i++)
1548 >                if (isClear(deathRow, i - beg))
1549 >                    es[w++] = es[i];
1550 >            final int oldSize = size;
1551 >            System.arraycopy(es, end, es, w, oldSize - end);
1552 >            Arrays.fill(es, size -= (end - w), oldSize, null);
1553 >            // checkInvariants();
1554 >            return true;
1555 >        } else {
1556 >            if (modCount != expectedModCount)
1557 >                throw new ConcurrentModificationException();
1558 >            // checkInvariants();
1559 >            return false;
1560          }
1561      }
1562  
1563      @Override
1533    @SuppressWarnings("unchecked")
1564      public void replaceAll(UnaryOperator<E> operator) {
1565          Objects.requireNonNull(operator);
1566          final int expectedModCount = modCount;
1567 +        final Object[] es = elementData;
1568          final int size = this.size;
1569 <        for (int i=0; modCount == expectedModCount && i < size; i++) {
1570 <            elementData[i] = operator.apply((E) elementData[i]);
1571 <        }
1541 <        if (modCount != expectedModCount) {
1569 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1570 >            es[i] = operator.apply(elementAt(es, i));
1571 >        if (modCount != expectedModCount)
1572              throw new ConcurrentModificationException();
1543        }
1573          modCount++;
1574 +        // checkInvariants();
1575      }
1576  
1577      @Override
# Line 1549 | Line 1579 | public class ArrayList<E> extends Abstra
1579      public void sort(Comparator<? super E> c) {
1580          final int expectedModCount = modCount;
1581          Arrays.sort((E[]) elementData, 0, size, c);
1582 <        if (modCount != expectedModCount) {
1582 >        if (modCount != expectedModCount)
1583              throw new ConcurrentModificationException();
1554        }
1584          modCount++;
1585 +        // checkInvariants();
1586 +    }
1587 +
1588 +    void checkInvariants() {
1589 +        // assert size >= 0;
1590 +        // assert size == elementData.length || elementData[size] == null;
1591      }
1592   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines